c - 为结构中的结构数组动态分配内存
问题描述
我有一个棘手的问题,并尝试用一个简短的例子来解释它。
我想要这样的结构:
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);
}
我该如何编程?我在网上搜索,但找不到解决方案。我只找到了零件,但我无法解开它。
安德烈
解决方案
虽然允许将具有未指定长度的数组的结构作为最后一个成员,但不允许这样的结构成为数组的成员。
由于您正在为这些数组动态分配空间,因此将cars
andseats
成员声明为指针:
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;
};
推荐阅读
- python - 如何从 qlineedit 获取所有文本
- python - 如何从文件名中提取特定字符串?
- javascript - ...属性在 react-native 功能组件中
- python - h2o 数值列被转换为枚举
- c# - 如何知道在 EF 中执行查询的位置
- firebase - Flutter Firestore 添加数据
- c++ - 结构中的位是否保证是连续的?
- amazon-web-services - Sendy '与 Amazon SNS API 通信时出错:执行此请求时出现问题'
- javascript - CORS 不工作(失败)net::ERR_FAILED)
- linux - 在 ubuntu 上查找文件