C语言 如何为结构中的动态结构数组分配内存?

mmvthczy  于 2023-10-16  发布在  其他
关注(0)|答案(2)|浏览(123)

我有下面的结构,我试图分配空间的结构区下面。
目前,我正在为该区域分配空间:

  1. zone *zones = (zone*)malloc(sizeof(zone) + (sizeof(school)*3));

假设,我有3所学校和3个比赛在每个学校

  1. typedef struct competition {
  2. int prize_1;
  3. int prize_2;
  4. int prize_3;
  5. } competition;
  6. typedef struct school {
  7. int school_id;
  8. competition *competitions;//[Singing, Dancing, Soccer....]
  9. } school;
  10. typedef struct zone {
  11. school *schools; //[School 0, School 1, School 2.....];
  12. } zone;

当我尝试访问时:

  1. school *cs = &(zones->school[0]); //Get the appropriate school
  2. int schoolId = cs->school_id; //get the school id of a school

我得到一个分段错误。我知道我没有为Zone正确分配内存,但我不确定如何正确分配内存

wvyml7n5

wvyml7n51#

schools成员没有指向任何地方,因此尝试解引用该指针会触发undefined behavior
您需要首先为区域分配空间,然后为它指向的学校数组分配空间:

  1. zone *zones = malloc(sizeof(zone));
  2. zones->schools = malloc(sizeof(school)*3);
hkmswyz6

hkmswyz62#

要使用分配算法,您需要尽可能使用灵活的数组成员而不是指针,因为它简化了分配和释放。

  • 记住还要存储已分配对象的数量。
  • 始终检查分配错误并提供错误处理。
  1. typedef struct competition {
  2. int prize_1;
  3. int prize_2;
  4. int prize_3;
  5. } competition;
  6. typedef struct school
  7. {
  8. int school_id;
  9. size_t numCompetitions;
  10. competition competitions[];
  11. } school;
  12. typedef struct zone
  13. {
  14. size_t numSchools;
  15. school *schools[];
  16. } zone;
  17. school *allocateSchool(size_t numCompetitions)
  18. {
  19. school *sch = malloc(sizeof(*sch) + numCompetitions * sizeof(sch -> competitions[0]));
  20. if(sch) sch -> numCompetitions = numCompetitions;
  21. return sch;
  22. }
  23. zone *allocateZones(size_t numZones)
  24. {
  25. zone *zn = malloc(sizeof(*zn) + numZones * sizeof(zn -> schools[0]));
  26. if(zn) zn -> numSchools = numZones;
  27. return zn;
  28. }
展开查看全部

相关问题