The use of char data[0 in variable-length array struct in C language __c language

Source: Internet
Author: User

Absrtact: In actual programming, we often need to use variable-length arrays, but the C language does not support variable-length arrays. At this point, we can use the structure method to implement the C language variable length array.


struct MyData
{
int Nlen;
Char data[0];
};
In the structure, data is an array name, but the array has no elements; the real address of the array follows the mydata of the struct body, which is the address of the data after the structure (if the content assigned to the struct is larger than the actual size of the structure, the remainder of the item is the content of the volume) This declarative method can subtly implement the array extension in C language.
The actual use takes this way:
struct MyData *p = (struct MyData *) malloc (sizeof (struct MyData) +strlen (str))
This allows you to manipulate this str through p->data.

Program instance:


struct MyData
{
int Nlen;
Char data[0];
};

int main ()
{
int nlen = 10;
Char str[10] = "123456789";

cout << "Size of MyData:" << sizeof (MyData) << Endl;

MyData *mydata = (mydata*) malloc (sizeof (MyData) + 10);
memcpy (Mydata->data, str, 10);

cout << "MyData ' s Data is:" << mydata->data << Endl;

Free (myData);

return 0;
}

Output:
Size of Mydata:4
MyData "s Data is:123456789

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.