Recently in the "Deep Exploration of C + + object Model", for the use of the struct, found some places worthy of our reference, hereby share with you, this content contains some information collected online, but also thanks to the author of the information provided.
The original text reads as follows:
For example, placing an array of single elements at the end of a struct so that each struct objects can have a variable-sized array.
Code
struct Mumble {
Stuff
Char pc[1]; };
Obtain a string from the file or standard input device, and then configure enough memory for the struct itself and the string
struct mumble *pmumbl= (struct mumble*) malloc (sizeof (struct (mumble))) +strlen (string) +1;
strcpy (pmumbl->pc,string);
For this passage, I was just beginning to think of the solution, after a study, only to know that this is the so-called flexible array usage. First, the concept of a flexible array is explained:
A flexible array (flexible array), also known as a scalable array, is actually a variable-length array that reflects the extreme pursuit of the C language for refining code. This code structure arises from the need for dynamic structures. For example, we need to store a dynamic-length string in the struct, when the flexible array can be used.
C99 uses an incomplete type to implement a flexible array, the standard form is as follows:
struct MYSTRUCT
{
int A;
Double b;
Char c[]; or Char c[0]; Other data types can also be used;
};
C does not occupy MyStruct space, just as a symbolic address exists, and must be the last member of the struct.
Example code:
#include <iostream> #include <malloc.h>using namespace std;typedef struct mystruct{ int A; Double b; Char c[];} Ms,*pms;int Main () { char c1[] = "short string."; Char c2[] = "This is a long string."; PMS pms1 = (PMS) malloc (sizeof (MS) + strlen (C1) + 1); if (NULL! = pms1) { pms1->a = 1; Pms1->b = one; strcpy (Pms1->c, C1); } cout<< "PMS1:" << pms1->a << "" <<pms1->b << "<<pms1->c< < Endl; PMS PMS2 = (PMS) malloc (sizeof (MS) +strlen (C2) + 1); if (NULL! = pms2) { pms2->a = 2; Pms2->b =; strcpy (pms2->c, C2); } cout<< "PMS2:" <<pms2->a << "<<pms2->b <<" "<<pms2->c< < Endl; Free (PMS1); Free (PMS2); return 0;}
Output:
Pms1:1 one short string.
Pms2:2 a long string.
Flexible arrays-read the Deep Exploration of C + + object Model (reprint)