Flexible Array Member (Zero Length Array) [duplicate]

随声附和 提交于 2019-11-30 09:03:54

问题


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?


回答1:


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

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

Since C doesn't really care that you are accessing elements beyond the end of the array, you just start with an array of size zero, 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;



回答2:


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.



来源:https://stackoverflow.com/questions/9816325/flexible-array-member-zero-length-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!