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

标签 c struct compiler-errors malloc initializer

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

编译器到达下一行时,将引发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/

相关文章:

c - 使用 iconv() 的 UTF-8 到 C/POSIX 语言环境转换失败

c - 错误 C2449 和错误 C2059

c - C 中使用变量或指针访问结构体成员

c - 使用 libconfig.h 的字符串和字符集问题

mysql - 如何在mariadb/mysql中解释语法错误1064

c - 如何使命令行中的 -D 值成为字符串?

c - 在执行procprob时,b可以是任何数据类型吗?

c - 指向结构行为的意外指针

c - [错误]:expected '(' before 'hours'

python - Qt5 qmake-找不到合适的Python 2版本