MALLOC结构指针数组VS结构的数组 [英] malloc an array of struct pointers vs array of structs
问题描述
有什么
struct mystruct *ptr = (struct test *)malloc(n*sizeof(struct test));
和
struct mystruct **ptr = (struct test *)malloc(n*sizeof(struct test *));
他们都做工精细,我只是好奇两人之间的实际差异。不第一个分配结构的数组,而第二个结构指针数组?另一种方式?此外,其中一个具有较小的内存占用?
They both work fine, I'm just curious about the actual difference between the two. Does the first one allocate an array of structs, whereas the second one an array of struct pointers? The other way around? Also, which one has a smaller memory footprint?
推荐答案
第一分配结构
的数组,其他分配指针数组结构
。 向右走,而在第二种情况下,你必须分配<$ C $;在第一种情况下,你可以通过指定 PTR [0] = .field1值写入领域C>结构
本身在做实际的写作了。
The first allocates an array of struct
, and the other allocates an array of pointers to struct
. In the first case, you can write to fields by assigning ptr[0].field1 = value;
right away, while in the second case you must allocate the struct
itself before doing the actual writing.
这是确定下降的malloc
导致C的演员,所以你可以写
It is OK to drop the cast of malloc
result in C, so you could write
struct mystruct **ptr = malloc(n*sizeof(struct test *));
for (int i = 0; i != n ; i++) {
ptr[i] = malloc(sizeof(struct test));
}
ptr[0]->field1 = value;
...
// Do not forget to free the memory when you are done:
for (int i = 0; i != n ; i++) {
free(ptr[i]);
}
free(ptr);
这篇关于MALLOC结构指针数组VS结构的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!