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

后端 未结 5 697
野性不改
野性不改 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:46

    In the first one there is actually a pointer allocated in struct queue, and sizeof(struct queue) == 2 * sizeof(int) + sizeof(q_info*)

    In the second one there is no pointer or anything named array really exists in struct queue, and sizeof(struct queue) == 2 * sizeof(int). This is known as a trick to conveniently reference the data before or later using array. I've used this trick in implementing a memory allocator.

提交回复
热议问题