I'm trying to read an arbitrary number of string items into an array of structs when my program initializes. I want to allocate heap memory for the
When the compiler gets to the following line, it throws an error: invalid initializer.
The first part of my code:
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;
}
}
...
What am I missing here?
The compiler output:
$ gcc -W -Wall vineyard.c
vineyard.c: In function ‘main’:
vineyard.c:30:32: error: invalid initializer
Plantation plantations[] = (Plantation *)malloc(sizeof(Plantation));
^
It also throws the same if I leave out typecasting.
$ gcc -W -Wall vineyard.c
vineyard.c: In function ‘main’:
vineyard.c:30:32: error: invalid initializer
Plantation plantations[] = malloc(sizeof(Plantation));
^~~~~~
Thanks!