在数组结构的malloc处出现无效的初始化编译器错误。

问题描述 投票:0回答:1

当我的程序初始化时,我试图在一个结构数组中读取任意数量的字符串项。我想为这个数组中的

当编译器编译到以下一行时,它抛出一个 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));
                                ^~~~~~

谢谢!我想在一个数组中读取一个任意数量的字符串项。

c struct compiler-errors malloc initializer
1个回答
0
投票

你正在定义 plantations 作为一个数组,而你正试图用一个指针初始化一个数组。 数组的初始化器必须是一个用括号括起来的初始化器列表。 更重要的是,虽然数组和指针是相关的,但它们不是一回事。

定义 plantations 作为一个指针而不是数组。

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

还有: realloc 可以改变所分配的内存的指向,所以你需要将返回值分配回来。

plantations = realloc(plantations, sizeof(Plantation) * plantationCount);

你也应该检查 mallocrealloc 错。

© www.soinside.com 2019 - 2024. All rights reserved.