C 0 Length Array

Source: Internet
Author: User

In C, the array size is fixed and has no variable length, and in order to achieve an array of variable lengths, a 0-length array is provided in such a way as to define a struct body:

struct Test
{
	int length;
	Char contents[0];
In this way, the structure itself length =sizeof (int), that is, an integer length, contents is not space, and then in the program call, you can use the following:

struct Test *t = (struct test*) malloc (sizeof (struct Test) +);
T->length = 10;
So this time, T occupies the space is sizeof (struct Test) + 10, the extra space just can have t->contents to point to, and the length of the array is t->length, so you can get to the dynamic array;

But there are drawbacks to this, which is that 0-length arrays can be used for heap space, but not for stack space, that is, if struct test test; By this definition, the length of test is OK, and contents cannot be allocated by the program to get extra space, that is, at this time, the length of the test is just sizeof (struct test), which is the size of the sizeof (int).


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.