我正在尝试将结构数组初始化为零。由于某种原因,我收到错误“预期表达式”。我的代码有什么问题吗?
struct mystruct {
double a;
double arr[2];
}
int main() {
struct mystruct *array = (struct mystruct*)malloc(3 * sizeof(struct mystruct));
for (int i = 0; i < 3; i++) {
array[i] = { 0 };
}
return 0;
}
最佳答案
聚合初始化仅适用于……初始化:
struct mystruct x = {0}; // initialization
没有这样的赋值语法。
但您不需要,只需使用 calloc
而不是 malloc
来动态分配、清零内存。
struct mystruct* array = calloc(3, sizeof(struct mystruct));
关于c - 结构体数组的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41817704/