Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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
like image 526
Shraddha Avatar asked Jan 30 '13 16:01

Shraddha


1 Answers

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.

like image 105
Carl Norum Avatar answered Oct 22 '22 11:10

Carl Norum