Flexible array Structure members
The last element in the struct allows an array of unknown size, which is called a flexible array member, but a flexible array member in the structure must precede at least one other member. Flexible array members allow a variable-sized array to be included in the structure. The size of this structure returned by sizeof does not include the memory of a flexible array. Structures that contain flexible array members are dynamically allocated with the malloc () function, and the allocated memory should be larger than the size of the structure to accommodate the expected size of the flexible array.
The magic of the structural body's length--an array of 0 elements
Sometimes we need to produce a structure that implements a variable-length structure. How to achieve it?
look at the definition of this structure:
typedef struct ST_TYPE
{
int ncnt;
int item[0];
}type_a;
(some compilers will fail to compile the error can be changed to:)
typedef struct ST_TYPE
{
int ncnt;
int item[];
}type_a;
so we can define a variable-length structure, with sizeof (TYPE_A) to get only 4, that is sizeof (NCNT) =sizeof (int) thatAn array of 0 elements does not occupy space, and then we can do a variable length operation.
C Language:
type_a *p = (type_a*) malloc (sizeof (TYPE_A) +100*sizeof (int));
C + + language:
type_a *p = (type_a*) new char[sizeof (type_a) +100*sizeof (int)];
so we have a 100-type_a type of thing with P->item[n] to simply access variable-length elements, the principle is very simple
, allocated more than sizeof (TYPE_A) after the memory int item[]; it has meaning, it points to the int ncnt; The following is not
There is memory required, and in the allocation of more allocated memory can be manipulated by it, is a very useful technique.
and the release is equally simple:
C language version:
Free (p);
C + + language version:
delete []p;
Finally, a "member array and pointer in the C-language structure" http://coolshell.cn/articles/11377.html
Some problems about flexible arrays