Flexible array member (flexible array member)-C99-ZZ

Source: Internet
Author: User

Learning Flexible array member is a result of reading Redis source, sds.h in the beginning.

==============================================================================================

Before you tell a flexible array member, first introduce the incomplete type (incomplete type). An incomplete type is a type that lacks sufficient information such as length to describe a complete object.

6.2.5 Types

Incomplete Types (Types that describe objects but lack information needed to determine their sizes).

C is the same as C + + with respect to the semantics of incomplete types.

A forward declaration is a common, incomplete type:

    1. Class Base;
    2. struct test;

Base and test only give a declaration, not a definition. Incomplete types must be supplemented in some way in order to be instantiated using them, otherwise they can only be used to define pointers or references , because the pointer or reference itself, not the base or test object, is instantiated at this time.

An array of unknown lengths also belongs to the incomplete type:

    1. extern int a[];

extern cannot be removed because the length of the array is unknown and cannot appear as a definition. an array of incomplete types can be supplemented in several ways in order to be used, and the initialization of curly braces is one of the ways:

    1. int a[] = {10, 20};

The flexible array member (flexible array member) is also known as a scalable array member, and its appearance reflects the extreme pursuit of the refined code by C programmers. This code structure arises from the need for dynamic structures. In daily programming, it is sometimes necessary to store a string of dynamic length in a struct, and the general practice is to define a pointer member in the struct that points to the dynamic memory space where the string resides, for example:

    1. struct test
    2. {
    3. int A;
    4. double b;
    5. Char *p;
    6. };

P points to a string. This method causes the string to be separated from the struct, and is not conducive to manipulation, if the string is linked directly to the struct, is not it better? Therefore, you can modify the code to this:

    1. Char a[] = "Hello World";
    2. struct Test *pnttest = ( struct test*) malloc ( sizeof ( struct test) + strlen (a) + 1);
    3. strcpy (Pnttest + 1, a);

This way, (char*) (Pnttest + 1) is the address of the string "Hello World" ( p is ignored). At this point P becomes superfluous and can be removed. However, another problem arises: the constant Use (char*) (Pnttest + 1) is inconvenient. If you can find a method that can directly reference the string, without taking up the space of the structure, it is perfect, the code structure that conforms to this condition should be a non-object symbolic address, placing a 0-length array at the tail of the struct is a wonderful solution. However, the C + + standard does not define an array of length 0, so some compilers use 0-length array members as their own non-standard extensions, for example:

    1. struct test
    2. {
    3. int A;
    4. double b;
    5. Char c[0];
    6. };

c is called a flexible array member , if the pnttest point to the dynamic allocation of memory as a whole, C is a length can dynamically change the structure of the member, the word flexible is derived from this. The length of c is 0, so it does not occupy the test space, and Pnttest->c is the first address of "Hello World", no need to use (char*) (pnttest + 1) so ugly syntax.

Given the important role that this code structure produces, C99 even earns it the standard:

6.7.2.1 Structure and Union specifiers

As a special case, the last element of a structure with more than one named member May has an incomplete array type; This is called a flexible array member.

C99 uses an incomplete type to implement a flexible array member , which is the standard form:

    1. struct test
    2. {
    3. int A;
    4. double b;
    5. Char c[];
    6. };

C also does not occupy test space , only as a symbolic address exists, and must be the last member of the struct. Flexible array members can be used not only for character arrays, but also for elements of other types of arrays, such as:

    1. struct test
    2. {
    3. int A;
    4. double b;
    5. float c[];
    6. };

The standard form should be used as much as possible, and the pointer method can be used in non-C99 situations. Some people use char a[1], which is very undesirable, to take such a as a flexible array member will occur out of bounds behavior, although the C + + standard does not stipulate that the compiler should check out of bounds, but there is no rule can not check out of bounds, for a small pointer space to sacrifice portability, is not worth it.

How does a flexible array work? Look at the following example:

    1. typedef struct St_type
    2. {
    3. int i;
    4. int a[0];
    5. }type_a;

Some compilers will fail to compile the error can be changed to:

    1. typedef struct St_type
    2. {
    3. int i;
    4. int a[];
    5. }type_a;

So that we can define a variable-length structure, with sizeof (TYPE_A) to get only 4, is
sizeof (i) =sizeof (int). The array of the 0 elements does not occupy a space,Then we can do the variable-length operation. Wildcard
Allocate memory to the struct by following an expression:
type_a *p = (type_a*) malloc (sizeof (TYPE_A) +100*sizeof (int));This allows us to allocate a block of memory for the struct pointer p. With P->item[n], you can easily access variable-length elements.
but then we used sizeof (*P) to test the size of the structure, and found that it was still 4. Isn't it weird? We
Did you allocate space for this array?
Don't worry, just remember the "mold" we talked about earlier. When defining this structure, the size of the mold is
Determined the size of the memory that does not contain a flexible array. Flexible arrays are only non-staff and do not account for structure. Just saying
You need to use a flexible array as a member of the struct, that's all. Again, the white point, the flexible array is actually
The structure has nothing to do with it, just "trickery", not a formal member of the structure.
What needs to be explained is: C89 does not support this kind of thing, C99 it as a special case to join the standard. However, C99
The incomplete type is supported, not the zero array,shape with int item[0]; This form is illegal, C99 supported in the form of an int item[]; only some compilers have int item[0]; As a non-standard extension to support, and this nonstandard extension was already in place before C99 was released, and after C99 was released, some compilers merged the two into one. Of course, since memory is allocated with the malloc function, it is definitely necessary to use the free function to release memory:
Free (p);
After the above explanation, I believe you have mastered this seemingly mysterious thing. But it doesn't matter if it's not mastered, it's very seldom used.[Note: In fact, a lot of use, Redis source Sds.h a ...]

"Flexible Array structure members"

In C99, 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. 】

C language version:

Type_a *p = (type_a*) malloc (sizeof (TYPE_A) +100*sizeof (int));

C + + language version:

Type_a *p = (type_a*) new char[sizeof (type_a) +100*sizeof (int)];

And the release is equally simple:

C language version:

Free (p);

C + + language version:

delete []p;

http://blog.csdn.net/sunlylorn/article/details/7544301

Flexible array member (flexible array member)-C99-ZZ

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: info-contact@alibabacloud.com 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.