Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[CPP]View PlainCopyprint?
Today, when looking at a piece of code to implement a variable-length array with the structure of the writing, at first because of the forgotten this technology, so the author of the old source error, finally after I thought, finally think of the previously seen with a struct to implement variable-length array technology. Here is a very clear article I found on the Internet.
In practical 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 of the 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, and the real address of the array is immediately after the struct MyData, and this address is the address of the data behind the struct (if the content assigned to the struct is larger than the actual size of the struct, the remainder is the contents of the data) This kind of declarative method can skillfully implement the array extension in C language.
Actually take this:
[CPP]View PlainCopyprint?
- struct MyData *p = (struct MyData *) malloc (sizeof (struct MyData) +strlen (str))
This allows the STR to be manipulated by P->data.
Program Examples:
#include <iostream>using namespacestd; structMyData {intNlen; Chardata[0]; }; intMain () {intNlen =Ten; Charstr[Ten] ="123456789"; cout<<"Size of MyData:"<<sizeof(MyData) <<Endl; MyData*mydata = (mydata*)malloc(sizeof(MyData) +Ten); memcpy (MyData->data, str,Ten); cout<<"MyData ' s Data is:"<< Mydata->data <<Endl; Free(MyData); return 0; }
Output:
Size of Mydata:4
MyData "s Data is:123456789
Original link: http://www.2cto.com/kf/201312/261179.html
PS: The pointer must be defined at the end of the struct, and the type of the pointer may not be char.
The use of Char data[0] in a variable-length array struct of C language