Flexible member of an array (zero-length array)

Regarding the GCC Zero Length Array explanation:

This is especially useful when the struct is the header for a variable-length object. This is definitely my business. Also, I'm interested in aligning my structures on a heap.

In this case, I still don't understand what is useful for arrays of zero length. How are they related to this particular situation?

EDIT:

Can I put as much β€œdata” as I want?

+4
source share
2 answers

This basically allows you to have a structure with a variable length array at the end:

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

Since C really doesn't care about you accessing elements outside of the array, you just start with a zero-sized array, and then allocate enough memory to handle all the elements you really want:

 struct X *xp = (struct X *)malloc(sizeof(struct X)+10*sizeof(int)); xp->rest[9] = 0; 
+2
source

The memory returned with malloc() that you assigned to the pointer to the structure with a zero-length array element will be aligned in memory ..., which is required by the C99 specification. Thus, there is no problem with imposing a structure with an array of zero length from memory allocated from the heap via malloc() .

If you encounter a problem, you will try to overlay your structure on top of some raw buffer in memory that comes from a packaged or not traditionally aligned data source, such as a file header, memory-mapped interface, etc. In these cases, using an array with zero length for variable-length data processing may be a bad idea, because the data cannot be aligned according to the default alignment parameters of the platform, and thus the offset to the array is not goes to the correct results.

0
source

Source: https://habr.com/ru/post/1402803/


All Articles