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

后端 未结 5 717
野性不改
野性不改 2020-12-06 08:35

How do the two implementations differ:

struct queue {
    int a;
    int b;
    q_info *array;
};

and

struct queue {
    i         


        
5条回答
  •  忘掉有多难
    2020-12-06 08:54

    These are completely different things:

    • The first contains a pointer to an external array.
    • the second is an inline array that happens to have zero elements.

    The reason people do this is it's more space-efficient. You simply over-allocate the memory the struct needs, and then pretend the array has more elements then declared - the compiler won't mind (usually).

    It also means you have one less pointer to dereference through, and you can allocate and free the memory for the struct and the array all in one.

    Obviously, this trick only works when the array is the last element in the struct.

提交回复
热议问题