简体   繁体   中英

What's the difference between char [] and char * in struct?

There is a struct like this:

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

And the result of printf ("%d\\n", sizeof(struct sdshdr)); is 8. If I change char buf[] to char * , the result would be 16. Why is char buf[] taking no space here( sizeof(int) is 4)? When shoud I choose char buf[] over char *buf ?

The construct with the empty brackets [] is allowed as the last element of the struct . It lets you allocate additional space beyond sizeof(sdshdr) for the elements of the array, letting you embed the array data with the array itself.

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

Taking " char[] " more generally:

char[] will actually allocate a number of characters inside the struct. (A struct with char x[17] will grow by 17 bytes and so on.) A char* will just hold a pointer.

An actual char x[] (with no size specified - and I think the same goes for size 0) at the end of the struct is a special case called a "flexible array member" and is discussed in the linked question and in the other answer.

Remember also that sizeof needs to be determined at compile time. Since char buf[] is a flexible array member it's size cannot be known at compile time, therefore will be omitted from the calculation of sizeof .

char * is a pointer to a char variable, and it's size is known so is included (however that is the size of the pointer not the array it points to).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM