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

后端 未结 5 712
野性不改
野性不改 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 09:01

    For the zero-sized array member, you can, when you allocate the structure, allocate more memory than the size of struct queue (for example malloc(sizeof(struct queue) + sizeof(q_info) * 10)) to have a contiguous area of memory you can use. Then the array will be part of that memory allocated, and for the example allocation you have ten q_info entries in it.

    For the pointer, you have to make two allocations, one for the queue structure, and one for the array member. You of course have to call free twice, once for the array pointer and once for the structure.

    However, once allocated both can be used the same.

提交回复
热议问题