Some problems about flexible arrays

Source: Internet
Author: User

Flexible array Structure members
The last element in the struct agrees to be an array of unknown size, which is called a flexible array member, but a flexible array member in a struct must precede at least one other member. A flexible array member agrees to include a variable-sized array in the structure. sizeof returns such a structure size that does not include the memory of a flexible array.

Structures that include members of flexible arrays use the malloc () function for dynamic allocation of memory, 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 create a structure. A variable-length structure is implemented.

How to achieve it?

look at the definition of this structure:
typedef struct ST_TYPE
int ncnt;
int item[0];
(some compilers will fail to compile error can be changed to:)
typedef struct ST_TYPE
int ncnt;
int item[];
This allows us to define a variable-length structure. With sizeof (TYPE_A) only 4, is the sizeof (NCNT) =sizeof (int) thatAn array of 0 elements does not occupy space, and then we are able to do the 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 memory can be manipulated by it, is a very useful technique.

and release the same simple:
C language version:
Free (p);
C + + language version:
delete []p;

Finally, a "member array and pointer in the C-language structure"

Some problems about flexible arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.