Support for variable-length arrays (incomplete arrays) in C 99

Source: Internet
Author: User
Tags array definition

 

In standard C or C ++, int array [0]; is invalid because it does not support arrays with a length of 0. However, some compiler Extensions support arrays with a length of 0.

 

In C, the 0-length array is mainly used as the last member of the struct, then use it to access a piece of memory after the struct object (usually the dynamically allocated memory ). Due to its non-standard nature, avoid using an array of 0 length in the program. As a replacement, you can use an incomplete array in the C99 standard to replace the array definition with a length of 0. For example:

 

Struct X {

/* Members */

Int array [];/* Do not write int array [0]; since it is not standard .*/

};

General applications:

 

 

Struct {

Int a, B;

Char data [0];

/* Do not write fields below */

};

 

Struct A * p;

 

Int n= 100, I;

P = malloc (sizeof (struct A) + n );

For (I = 0; I <n; ++ I)

P-> data [I] = 1;

 

From redxu's column

Related Article

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.