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);
instead of
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.
Starting with C99 you can drop zero from the declaration of the array member:
struct queue {
int a;
int b;
q_info array[];
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…