C struct whose field name can be referenced contextually

时间:2016-12-09 12:46:46

标签: c struct

I have a structure

typedef struct foo {
    int type;
    int id[2];
    int data[8];
} Foo;

This can be of two different types. If type==1, then it has a single 32 bit id and 8 bytes of storage, but if type==2, then it has a 64 bit id, but can only store seven bytes of data. So the two types take up identical space in memory. But I'd like to do

Foo foo1;
foo1.type = 1;
foo1.id = 1;
foo1.data = eightbytes;

Foo foo2;
foo2.type = 2;
foo2.id = 2;
foo2.data = sevenbytes;

Is this possible in C?

1 个答案:

答案 0 :(得分:3)

Yes, that is possible:

typedef struct foo {
    int type;
    union {
        struct {
            int id;
            int data[8];
        } t1;
        struct {
            long id;
            int data[7];
        } t2;
    } u;
} Foo;

Your usage would become:

Foo foo1;
foo1.type = 1;
foo1.u.t1.id = 1;
foo1.u.t1.data = eightbytes;

Foo foo2;
foo2.type = 2;
foo2.u.t2.id = 2;
foo2.u.t2.data = sevenbytes;