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!
You're defining plantations
as an array, and you're trying to initialize an array with a pointer. An initializer for an array must be a brace enclosed list of initializers. More importantly, while arrays and pointers are related, they are not the same thing.
Define plantations
as a pointer instead of an array:
Plantation *plantations = malloc(sizeof(Plantation));
Also, realloc
can change where the allocated memory points to, so you need to assign the return value back:
plantations = realloc(plantations, sizeof(Plantation) * plantationCount);
You should also check the return value of malloc
and realloc
for errors.