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