繁体   English   中英

C,如何为另一个结构内部的结构数组正确分配空间量?

[英]C, How to malloc the correct amount of space for an array of a struct inside another struct?

我有两个结构。 我正在尝试在另一个结构“结构巢”中制作“结构鸟”的数组。

创建嵌套结构时,我很难为Bird数组分配正确的空间量。

下面是我的代码。

struct bird {
  int value;
};
typedef struct bird bird;

struct nest {
  int nb_birds;
  bird * * birds;     //bird * = points to the bird struct, * birds = Array with size unknown
};
typedef struct nest nest;

nest * create_nest(int nb_birds) {
  nest * n = (nest *) malloc(sizeof(nest));
  n->nb_birds = nb_birds;

   //This is where I am stuck
  ***n->birds = (bird *) malloc(sizeof(bird) * nb_birds);*** 


  int i;
  for(i = 0; i < nb_birds; i++)
    n->birds[i]=NULL;
  return n;
}

您想要分配nb_birds 指针数组到bird结构,所以要分配的大小是nb_birds * sizeof(bird *)

然后,您要存储指向此数组的指针,因此强制转换应为第一个元素的地址bird *地址,即bird **

因此,

n->birds = (bird **) malloc(sizeof(bird *) * nb_birds);

ps如果要分配ptr指向的N对象,则可以编写或至少考虑为

ptr = (typeof(ptr)) malloc(sizeof(*ptr) * N);

更新:

应当注意, malloc返回void *指针,该指针与任何指针类型都兼容,而无需显式转换。 因此,引用的程序行可以短至

ptr = malloc(N * sizeof(*ptr));

尽管有些程序员非常了解此void *属性,但他们还是强烈希望在这种情况下使用显式强制转换。 我不是其中之一,但是我将这种类型转换归为样式偏好(例如sizeof运算符的() )。 因此我在上面的代码中保留了强制类型转换,因为OP使用了它,我认为这是他的选择。

没什么需要(至少对于答案的完整性和进一步的读者而言)要注意,这种强制转换是不必要过度的

谢谢Paul Ogilviechux在评论中提供耐心的笔记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM