How do the two implementations differ:
struct queue {
int a;
int b;
q_info *array;
};
and
struct queue {
int a;
int b;
q_info array[0];
};
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[];
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With