如何显示一个结构的另一个结构的列表?

How to display a structure of a list of another structure?

我正在做一个小项目,其中有一个汽车结构(年份、品牌等)和一个包含汽车的集合结构,如何在集合中显示汽车?

在我的Car.h中我定义了:

struct CarP;
typedef struct CarP * Car;
typedef const struct CarP * constCar;

Car car_createCopy(constCar c); //returns a copied car from c 
void display_car(constCar c);

在我的 Collection.h 文件中我定义了:

struct CollectionP;
typedef struct CollectionP * Collection;
typedef const struct CollectionP * constCol;

并在 Collection.c 中:

struct CollectionP{
    int nbCars;
    Car * carList;
}

int getNbCars(constCol c){
    return c -> nbCars;
}

void add_car(Collection c, constCar car){
    int nbCar = getNbCars(c);
    if(nbCar == 0)
        c -> carList = malloc(sizeof(car));
    else{
        c -> carList = realloc(c -> carList,(nbCar+1)*sizeof(car));
        c -> carList[nbCar] = car_createCopy(car);
    }
    c -> nbCars++;
}

void display_col(constCol c){
    int nbCar = getNbCars(c);
    for(int i = 0; i < nbCar; i++)
        display_car(c -> carList[i]);
}

将一些汽车添加到集合中后,我尝试调用显示函数,我只得到一辆汽车,品牌为空,其他字段的值为不同的数字,然后程序因分段错误而停止。

这是错误的。 (见下文 // HERE):

void add_car(Collection c, constCar car){
    int nbCar = getNbCars(c);
    if(nbCar == 0)
        c -> carList = malloc(sizeof(car));
    else{
        c -> carList = realloc(c -> carList,(nbCar+1)*sizeof(car));
        c -> carList[nbCar] = car_createCopy(car);  // HERE
    }
    c -> nbCars++;
}

那条标记线负责将汽车副本放入列表。但它永远不会在第一次添加时执行。它应该被移动,特别是在 else 块之后和外部。

void add_car(Collection c, constCar car){
    int nbCar = getNbCars(c);
    if(nbCar == 0)
        c -> carList = malloc(sizeof(car));
    else{
        c -> carList = realloc(c -> carList,(nbCar+1)*sizeof(car));
    }
    c -> carList[nbCar] = car_createCopy(car);  // FIXED
    c -> nbCars++;
}

也就是说,这里有很多地方需要错误检查,您对 realloc 的使用应该通过一个临时指针,以免您将分配的列表丢失给错误的 NULL 结果。但是你的问题的核心正如我上面所展示的那样。