An empty array is an array with a subscript of 0, for example, a [0]. In the function, it makes no sense to declare an empty array. Of course, it cannot be compiled. In a class or struct, it can be declared in this way.
Struct ast_exten {
Char * exten;
Char stuff [0];
};
Another example:
Struct ast_include {
Char * name;
Char * rname;
Char stuff [0];
};
Struct ast_ignorepat {
Const char * registrar;
Struct ast_ignorepat * next;
Char pattern [0];
};
This is a widely used and common technique used to form a buffer zone. Compared with pointers, null arrays have the following advantages:
1. Initialization is not required. The array name is directly the offset.
2. No space is occupied. The pointer needs to occupy the int length space, and the empty array does not occupy any space.
"This array does not occupy any memory", which means this structure saves space; "The memory address of this array is the same as the address of the element following it", meaning no Initialization is required, the array name is the address of the following element, which can be directly used as a pointer.
This method is most suitable for creating dynamic buffer. Because space can be allocated as follows:
Malloc (sizeof (struct XXX) + buff_len );
Are there any advantages? The structure of the buffer and the buffer are directly allocated. It is also very convenient to use, because the empty array is actually an array of buff_len length.
The following benefits:
One allocation solves the problem, saving a lot of trouble. We all know that in order to prevent memory leakage, if it is divided into two distributions (struct and buffer), if the second malloc fails, you must roll back and release the first allocated struct. This causes coding trouble. Second, after the second buffer is allocated, if a pointer is used in the structure, the pointer must be assigned a value. Similarly, when the buffer is free, the pointer is free twice. If an empty array is used, all problems are solved once.
Secondly, we know that it is very difficult to manage small memory. If a pointer is used, the struct part of the buffer is small memory, if there is more in the system, it will seriously affect the memory management performance. If you use an empty array to allocate large blocks of struct and the actual data buffer at one time, this problem will not occur.
In this case, the use of empty arrays not only simplifies encoding, but also solves the problem of Small memory fragmentation and improves performance.