首页 > 解决方案 > 循环遍历一个动态分配的结构数组并填充每个结构

问题描述

在动态分配结构数组时,我正在努力使我的语法正确,然后我将循环遍历并传递给将从文件中填充结构的函数。任何帮助将不胜感激,因为我认为我误解了两个基本概念 1.如何最初将数组中的每个结构传递给函数 2.在函数中如何访问和分配结构字段的值。

这不会编译,这些是我得到的错误:

error: error: dereferencing pointer to incomplete type; 

对于三个字段(姓名、年龄、体重)中的每一个

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

标签: c

解决方案


请在代码中查看下面的注释

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

推荐阅读