Search code examples
cpointersmallocrealloc

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


I am working on a small project, in which I have a car structure(year, brand, etc..) and a collection structure that contains cars, how do I display the cars inside a collection?

in my Car.h I defined :

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

in my Collection.h file I defined :

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

and in 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]);
}

after adding some cars to the collection, I try to call the display function, I get only one car with null for brand and different numbers as values for other fields and then the program stops with a segmentation fault error.


Solution

  • This is wrong . (see // HERE below):

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

    That marked line is what is responsible for placing the car copy into the list. but it never executes on the first addition. It should be moved, specifically after, and outside, the else block.

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

    That said, there are a ton of places in this that need error checking, and your usage of realloc should be going through a temporary pointer, lest you lose your allocated list to a faulty NULL result. But the core of your problem is as i showed above.