Flexible Array Member (Zero Length Array) [duplica

2020-02-12 13:27发布

In reference to GCC's Zero Length Array explanation:

This is particularly useful in the case when a struct is a header for a variable-length object. This is exactly my case. Furthermore, I am concerned with the alignment of my structs in the heap.

In this case, I still really do not understand what's useful about zero length arrays. How are they related to this particular situation?

EDIT:

Is it that I can put as much "data" as I want in there?

2条回答
我命由我不由天
2楼-- · 2020-02-12 13:44

The memory returned from malloc() that you will assign to a pointer to the struct with the zero-length array member will be aligned memory ... that's required by the C99 specification. So there is no issue overlaying a struct with a zero-length array over memory allocated from the heap via malloc().

Where you would run into trouble would be attempting to overlay your struct over some raw buffer in memory that came from a packed or non-traditionally aligned data-source, such as a file-header, memory-mapped hardware interface, etc. In those cases, using a zero-length array to handle the variable-length data can be a bad idea since the data may not be aligned according to the default alignment parameters of the platform, and thus offsetting into the array will not yield the correct results.

查看更多
聊天终结者
3楼-- · 2020-02-12 13:53

Basically it allows you to have a structure with a variable length array at the end:

struct X {
  int first;
  int rest[0];
};

An array size of 0 is not actually valid (although it is allowed as a gcc extension). Having an unspecified size is the correct way. Since C doesn't really care that you are accessing elements beyond the end of the array, you just start with an undefined array size, and then allocate enough memory to handle however many elements you actually want:

struct X *xp = (struct X *)malloc(sizeof(struct X)+10*sizeof(int));
xp->rest[9] = 0;
查看更多
登录 后发表回答