在结构中使用指针和具有零元素的数组之间的区别 [英] Difference between use of pointer and array with zero elements in structs
问题描述
这两种实现有何不同:
struct queue {
int a;
int b;
q_info *array;
};
和
struct queue {
int a;
int b;
q_info array[0];
};
推荐答案
第二个 struct
不使用零元素数组 - 这是一个 C99 之前的技巧,用于制作灵活的数组成员.不同之处在于,在第一个片段中,您需要两个 malloc
- 一个用于 struct
,一个用于 array
,而在第二个中一个你可以在一个 malloc
中同时做到的:
The second struct
does not use an array of zero elements - this is a pre-C99 trick for making flexible array members. The difference is that in the first snippet you need two malloc
s - one for the struct
, and one for the array
, while in the second one you can do both in a single malloc
:
size_t num_entries = 100;
struct queue *myQueue = malloc(sizeof(struct queue)+sizeof(q_info)*num_entries);
代替
size_t num_entries = 100;
struct queue *myQueue = malloc(sizeof(struct queue));
myQueue->array = malloc(sizeof(q_info)*num_entries);
这可以让您节省释放的次数,提供更好的引用局部性,还可以节省一个指针的空间.
This lets you save on the number of deallocations, provides better locality of references, and also saves the space for one pointer.
从 C99 开始,您可以从数组成员的声明中删除零:
Starting with C99 you can drop zero from the declaration of the array member:
struct queue {
int a;
int b;
q_info array[];
};
这篇关于在结构中使用指针和具有零元素的数组之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!