Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between use of pointer and array with zero elements in structs

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];
};
like image 852
AbhinavChoudhury Avatar asked Dec 06 '22 05:12

AbhinavChoudhury


1 Answers

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 mallocs - 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[];
};
like image 59
Sergey Kalinichenko Avatar answered May 24 '23 01:05

Sergey Kalinichenko