Search code examples
carraysstructdynamically-generated

Allocate memory dynamically for an array of struct in a struct


I have a tricky problem and try to explain it in a short example.

I want to have such struct:

struct car_park{
   int count_of_cars;
   struct car{
       int  count_of_seats;
       struct seat{
           int size;
           int color; 
       }seats[];
   }cars[];
}

In a carpark there are a count of cars, each car has different count of seats and every seat has different parameter. Max count of cars is 100 and max count of seats is 6, but I don't want to use the arrays of cars and seats static. I would like to allocate the memory dynamically.

And: I want to use it in multiple functions.

void read_current_cars(struct car_park *mycars){
// read config file and allocate memory for the struct
...
}

void function_x(struct car_park *mycars){
//... use struct
}

void main(){
struct car_park my;

read_current_cars(&my);
function_x(&my);
}

How can I program it? I searched in web, but I can't find a solution. I found only parts, but I can't puzzle it.

Andre


Solution

  • While it is allowed to have a struct with an array with an unspecified length as the last member, such a struct is not allowed to be a member of an array.

    Since you're dynamically allocating space for these arrays, declare the cars and seats members as pointers:

    struct seat {
        int size;
        int color; 
    };
    
    struct car {
        int count_of_seats;
        struct seat *seats;
    };
    
    struct car_park {
        int count_of_cars;
        struct car *cars;
    };