Using the structure {... char arr [1]; } build?

I looked at a couple of instances in which I see something like char fl[1] in the following code snippet. I can not guess what could be the use of such a design.

 struct test { int i; double j; char fl[1]; }; int main(int argc, char *argv[]) { struct test a,b; ai=1; aj=12; a.fl[0]='c'; bi=2; bj=24; memcpy(&(b.fl), "test1" , 6); printf("%lu %lu\n", sizeof(a), sizeof(b)); printf("%s\n%s\n",a.fl,b.fl); return 0; } 

output -

 24 24 c<some junk characters here> test1 
+7
source share
3 answers

He called the "structure hulk" and you can read about it in the C FAQ . The general idea is that you allocate more memory than necessary for the structure, as indicated, and then use the array at the end, as if the length was greater than 1.

There is no need to use this hack, though, since it has been replaced with C99 + flexible array elements .

+7
source

Usually, the idea is to have a name for variable-sized data, such as a packet read by a socket:

 struct message { uint16_t len; /* tells length of the message */ uint16_t type; /* tells type of the message */ char payload[1]; /* placeholder for message data */ }; 

Then you create your buffer for such a struct and work with the data by indexing into a member of the array.

0
source

Please note that the code you wrote overwrites memory that you should not touch. memcpy() writes more than one character to one character array.

The use case for this most often looks like this:

 struct test *obj; obj = malloc(sizeof(struct test) + 300); // 300 characters of space in the // flexible member (the array). obj->i = 3; obj->j = 300; snprintf(obj->f, 300, "hello!"); 
0
source

All Articles