I am struggling with getting my syntax correct when dynamically allocating an array of structs that I will then loop through and pass to a function which will populate the struct from a file. Any help would be much appreciated because I think I am misunderstanding two essential concepts 1. how to initially pass each struct in the array to the function 2. once in the function how to access and assign the value of the struct field.
This won't compile and these are the errors that I'm getting:
error: error: dereferencing pointer to incomplete type;
for each of the three fields (name, age, weight)
warning: passing argument 2 of ârgetDogâ from incompatible pointer type [enabled by default] getDog(fp, dgy + i);
void getDog( FILE *fp, struct Dog *dgy )
{
char dogName[21];
double dogAge;
double dogWeight;
fscanf(fp, "%s%lf%lf", dogName, &dogAge, &dogWeight);
strcpy(dgy->name, dogName);
dgy->age = dogAge;
dgy->weight = dogWeight;
}
int main( int argc, char *argv[] )
{
FILE *fp = fopen( argv[ 1 ], "r" );
// read in number of dogs
int n;
fscanf( fp, "%d", &n );
struct Dog {
char name[21];
double age;
double weight;
};
struct Dog *dgy = (struct Dog *)malloc(n * sizeof(struct Dog));
for (int i = 0; i < n; i++ ) {
getDog(fp, dgy + i);
}
fclose(fp);
}