gpt4 book ai didi

c - 结构体数组的初始化

转载 作者:行者123 更新时间:2023-12-04 10:28:43 29 4
gpt4 key购买 nike

我正在尝试将结构数组初始化为零。由于某种原因,我收到错误“预期表达式”。我的代码有什么问题吗?

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com