gpt4 book ai didi

c - 无效的初始化程序编译器错误在结构数组的malloc

转载 作者:行者123 更新时间:2023-12-02 10:56:41 24 4
gpt4 key购买 nike

我正在尝试在程序初始化时将任意数量的字符串项读取到结构数组中。我想分配堆内存

编译器到达下一行时,将引发error: invalid initializer

我的代码的第一部分:

int main() {
printf("Work starts in the vineyard.\n");

typedef struct {
char* name[20];
unsigned int jobs;
}Plantation;

// read from list of plantations
FILE *plantationFile = fopen("./data/plantations.txt", "r");
if (plantationFile==NULL) {perror("Error opening plantations.txt."); exit(1);}

char line[20];
char *lp = line;
int plantationCount;
Plantation plantations[] = (Plantation *)malloc(sizeof(Plantation));
if (!feof(plantationFile)) {
int i = 0;
fgets(line, 20, plantationFile);
scanf(lp, "%i", &plantationCount);
realloc(plantations, sizeof(Plantation) * plantationCount);
while( !feof(plantationFile) ) {
fgets(line, 20, plantationFile);
strcpy(*(plantations[i].name), lp);
plantations[i].jobs = 1u;
++i;
}
}
...

我在这里想念什么?

编译器输出:
$ gcc -W -Wall vineyard.c
vineyard.c: In function ‘main’:
vineyard.c:30:32: error: invalid initializer
Plantation plantations[] = (Plantation *)malloc(sizeof(Plantation));
^

如果我不进行类型转换,它也会抛出相同的结果。
$ gcc -W -Wall vineyard.c
vineyard.c: In function ‘main’:
vineyard.c:30:32: error: invalid initializer
Plantation plantations[] = malloc(sizeof(Plantation));
^~~~~~

谢谢!

最佳答案

您正在将plantations定义为数组,并尝试使用指针初始化数组。数组的初始化程序必须是括号括起来的初始化程序列表。更重要的是,尽管数组和指针是相关的,但它们不是同一件事。

plantations定义为指针而不是数组:

Plantation *plantations = malloc(sizeof(Plantation));

另外, realloc可以更改分配的内存指向的位置,因此您需要将返回值分配回去:
plantations = realloc(plantations, sizeof(Plantation) * plantationCount);

您还应该检查 mallocrealloc的返回值是否有错误。

关于c - 无效的初始化程序编译器错误在结构数组的malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61511371/

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