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

时间:2018-11-11 12:24:41

标签: c arrays struct malloc

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

创建嵌套结构时,我很难为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;
}

1 个答案:

答案 0 :(得分:1)

您想将nb_birds指针数组分配给bird结构,因此要分配的大小为nb_birds * sizeof(bird *)

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

因此

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

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

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

更新

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

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

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

没有任何必要(至少为了答案的完整性和更多的读者)要注意,这样的转换是 不必要过度

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