0-length array usage in C language
In the C language, it is permissible to define 0-length arrays in structs and unions in the following two ways:
Char p[] or char p[0], this array is defined in the struct or union, and does not occupy space.
This is a common technique commonly used to form buffers. There are advantages to using an empty array compared to pointers:
1. Do not need initialization, the array name is directly the offset;
2. Without any space, the pointer needs to occupy an int length space, and the empty array does not occupy any space.
"This array does not occupy any memory", meaning that such a structure saves space; "The memory address of the array is the same as the address of the element behind him", meaning that the array name is the address of the subsequent element without initialization, and can be used directly as a pointer.
This is best for making dynamic buffer. Because you can allocate space like this:
malloc (sizeof (struct XXX) + Buff_len);
Does it look good? The structure of the buffer is directly allocated with a block of buffers. It is also very convenient to use, because now Kongsuzu actually becomes an array of buff_len lengths.
There are two points to this benefit:
One assignment solves the problem and saves a lot of trouble. It is known that in order to prevent memory leaks, if the second malloc fails, the first allocated struct must be rolled back if it is divided by two allocations (struct and buffer). This brings a coding problem. Second, after assigning the second buffer, if the structure uses a pointer, the pointer is also assigned a value. Also, in the free buffer, use the pointer two times free. If an empty array is used, all problems are resolved at once.
Second, we know that the management of small memory is very difficult, if the use of pointers, this malloc allocated space in the struct part of the small memory, in the system there are more and more will inevitably seriously affect the performance of memory management. There is no problem if the struct and the actual data buffer are allocated large chunks at once using an empty array.
Even though the advantages of a 0-length array are so many, use caution:
1.0 length array Not all C standards are supported, GNU C support, ANSI C is not supported, C + + is not supported.
2. If there is a case where there is only 0-length array element in the struct, this may cause errors to befall.
3. The 0-length array needs to be placed at the end of the struct.
0-length arrays in C language using instructions