Shraddha
Shraddha

Reputation: 2579

use of struct { ... char arr[1]; } construct?

I looked at couple of instances wherein I see something like char fl[1] in the following code snippet. I am not able to guess what might possibly be the use of such construct.

struct test
{
    int i;
    double j;
    char fl[1];
};

int main(int argc, char *argv[])
{
    struct test a,b;
    a.i=1;
    a.j=12;
    a.fl[0]='c';

    b.i=2;
    b.j=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

Upvotes: 7

Views: 1112

Answers (3)

Bill Lynch
Bill Lynch

Reputation: 81916

Note that the code you have written is overwriting memory that you shouldn't be touching. The memcpy() is writing more than one character into a one character array.

The use case for this is often more 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!");

Upvotes: 0

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

The idea usually is to have a name for variable-size data, like a packet read off 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 cast your buffer to such struct, and work with the data by indexing into the array member.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224844

It's called "the struct hack", and you can read about it at the C FAQ. The general idea is that you allocate more memory then necessary for the structure as listed, and then use the array at the end as if it had length greater than 1.

There's no need to use this hack anymore though, since it's been replaced by C99+ flexible array members.

Upvotes: 6

Related Questions