What is the difference between char [] and char * in a struct?

There is such a structure:

struct sdshdr { int len; int free; char buf[]; }; 

And the result is printf ("%d\n", sizeof(struct sdshdr)); is 8. If I changed char buf[] to char * , the result will be 16. Why does char buf[] not take up space here ( sizeof(int) is 4)? When shoud I select char buf[] over char *buf ?

+4
source share
3 answers

A construction with empty brackets [] allowed as the last element of a struct . It allows you to allocate additional space outside the sizeof(sdshdr) for array elements, allowing you to insert array data with the array itself.

Pointers, on the other hand, store data in a separately managed memory segment and require an additional free call at the end. Unlike the [] method, pointers allow you to have more than one array of variable length inside the same struct , and this element can be placed anywhere in the struct , and not just at the end of the struct .

+4
source

Taking " char[] " more broadly:

char[] will actually highlight multiple characters within the structure. (A structure with char x[17] will grow by 17 bytes, etc.) A char* will just contain a pointer.

The actual char x[] (without a specific size - and I think the same goes for size 0) at the end of the structure is a special case called the "flexible member of an array", and is discussed in a related question and in another answer.

+1
source

Remember also that sizeof must be determined at compile time. Since char buf[] is a flexible element of the array, its size cannot be known at compile time, so it will be omitted from the calculation of sizeof .

char * is a pointer to a char variable, and this size is known, therefore it is included (however, this is the size of the pointer, not the array it points to).

+1
source

All Articles