C、 如何在另一个结构中为一个结构的数组malloc正确的空间量?
我有两个结构。我正在尝试在另一个结构“struct nest”中创建一个“struct bird”数组 在创建嵌套结构时,我很难为bird数组分配正确的空间量 下面是我的代码C、 如何在另一个结构中为一个结构的数组malloc正确的空间量?,c,arrays,struct,malloc,C,Arrays,Struct,Malloc,我有两个结构。我正在尝试在另一个结构“struct nest”中创建一个“struct bird”数组 在创建嵌套结构时,我很难为bird数组分配正确的空间量 下面是我的代码 struct bird { int value; }; typedef struct bird bird; struct nest { int nb_birds; bird * * birds; //bird * = points to the bird struct, * birds = Array
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;
}
struct bird{
int值;
};
typedef结构鸟;
结构巢{
国际鸟类;
bird**birds;//bird*=指向bird结构,*birds=大小未知的数组
};
typedef结构嵌套;
鸟巢*创建鸟巢(int nb_鸟){
nest*n=(nest*)malloc(sizeof(nest));
n->nb_鸟=nb_鸟;
//这就是我被困的地方
***n->birds=(bird*)malloc(bird)*nb_birds);***
int i;
对于(i=0;ibirds[i]=NULL;
返回n;
}
您想要分配nb_birds
指向bird
结构的指针数组,所以分配的大小是nb_birds*sizeof(bird*)
然后您要存储指向该数组的指针,因此强制转换应该是第一个元素的地址--bird*
的地址,即bird**
因此,
n->birds = (bird **) malloc(sizeof(bird *) * nb_birds);
p、 如果您想分配N
对象,而ptr
指向这些对象,您可以编写,或者至少可以将其视为
ptr = (typeof(ptr)) malloc(sizeof(*ptr) * N);
更新:
应该注意的是,malloc
返回的void*
指针与任何指针类型兼容,无需显式强制转换。所以,引用的程序行可以短到
ptr = malloc(N * sizeof(*ptr));
一些程序员,尽管他们对这个void*
属性非常了解,但在这种情况下,他们强烈倾向于使用显式强制转换。我不是他们中的一员,但我认为这类演员是造型师іc偏好(比如()
对于sizeof
操作符)。所以我留下了上面的代码,因为OP使用它,我认为这是他的选择
尽管如此,我们还是需要(至少是为了答案的完整性和读者的进一步了解),注意这样的强制转换是不必要的,并且是过度的。
感谢您Paul Ogilvie和chux在评论中提供患者注释。您忘记了该代码片段的原型和/或功能声明…并且不要强制转换
malloc
的结果。它返回与任何指针类型兼容的void*
<代码>n->birds=malloc(sizeof(bird*)*nb_birds)代码>是答案所需的全部。同意,malloc返回的void*
的强制转换是多余的(我从来没有使用过)。但有些程序员更喜欢显式强制转换,我将这部分代码保留原样。无论如何,你的评论非常有用。ptr=malloc(sizeof*ptr*N)
更易于正确编码、检查和维护。不需要“类型”,如n->birds=malloc(sizeof*(n->birds)*nb_birds)
@chux您的评论与上面Paul Ogilvie的评论相同。但我添加了注释,因为这是一个热门话题:-)。感谢你在战争中帮助我克服懒惰。