简体   繁体   中英

Loop through a dynamically allocate array of structs and populate each one

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);
}

Please see comments below in the code

 // Some includes here - stdlib stdio

// This is needed for getDog
 struct Dog  {
    char name[21]; 
    double age;
    double weight;
 };
    

void getDog( FILE *fp, struct Dog *dgy ) 
{
//    char dogName[21]; Not required
//    double dogAge;
//    double dogWeight;

  // Check return value - ensure no buffer overrun
    if (fscanf(fp, "%20s%lf%lf", dgy->name, &dgy->age, &dgy->weight) != 3) {
       // Got an error - do summat about it
    }
//    strcpy(, dogName);  - Not required as fscanf does this for you
//    dgy->age = dogAge;
//    dgy->weight = dogWeight;
}

int main( int argc, char *argv[] )
{

    FILE *fp = fopen( argv[ 1 ], "r" );
    
// Is fp == NULL - if so error do summat about this
    // read in number of dogs
    int n;
    if ( fscanf( fp, "%d", &n ) != 1 ) {  // What is the point of || n < 1 ?
        invalidInput();
       // No point continuing to rest of code!
    }

    struct Dog *dgy = malloc(n * sizeof(struct Dog)); // Link below

    for (int i = 0; i < n; i++ ) {
        getDog(fp, dgy + i);
    }
    
    fclose(fp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM