为结构中的结构数组动态分配内存

Allocate memory dynamically for an array of struct in a struct

我有一个棘手的问题,我试着用一个简短的例子来解释它。

我想要这样的结构:

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

一个停车场里有几辆车,每辆车有不同的座位数,每个座位都有不同的参数。汽车的最大数量为 100,座位的最大数量为 6,但我不想使用静态的汽车和座位阵列。我想动态分配内存。

并且:我想在多个函数中使用它。

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

如何编程?我在网上搜索,但找不到解决方案。我只找到了零件,但我拼不出来

安德烈

虽然允许将具有未指定长度的数组的结构作为最后一个成员,但这样的结构不允许成为数组的成员。

由于您正在为这些数组动态分配 space,因此将 carsseats 成员声明为指针:

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