In the Linux kernel code I found the following thing which I can not understand.
struct bts_action {
u16 type;
u16 size;
u8 data[0];
} __attribute__ ((packed));
The code is here: http://lxr.free-electrons.com/source/include/linux/ti_wilink_st.h
What’s the need and purpose of an array of data with zero elements?
This is a way to have variable sizes of data, without having to call
malloc(kmallocin this case) twice. You would use it like this:This used to be not standard and was considered a hack (as Aniket said), but it was standardized in C99. The standard format for it now is:
Note that you don’t mention any size for the
datafield. Note also that this special variable can only come at the end of the struct.In C99, this matter is explained in 6.7.2.1.16 (emphasis mine):
Or in other words, if you have:
You can access
var->datawith indices in[0, extra). Note thatsizeof(struct something)will only give the size accounting for the other variables, i.e. givesdataa size of 0.It may be interesting also to note how the standard actually gives examples of
mallocing such a construct (6.7.2.1.17):Another interesting note by the standard in the same location is (emphasis mine):