C struct,其字段名称可以在上下文中引用

标签 c struct

我有一个结构

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

这可以是两种不同的类型。如果 type==1,那么它有一个 32 位的 id 和 8 个字节的存储空间,但是如果 type==2,那么它有一个 64 位的 id,但是只能存放七个字节的数据。所以这两种类型在内存中占用相同的空间。但我想做

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

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

这在 C 中可能吗?

最佳答案

是的,这是可能的:

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

您的用法将变为:

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;

关于C struct,其字段名称可以在上下文中引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41060857/

相关文章:

c - 使用 radio 调制解调器可以使用的最快、可靠的波特率是多少?

c - 尝试释放以前的 malloc 时出错

http - 在结构中设置值失败

c - 带有位域的奇怪大小的结构

c# - 将(结构的)实例方法传递给 ThreadStart 似乎更新了一个虚假实例,因为原始实例不受影响

c - 将整数表示为链表

c++ - 比 SetPixel() 更快的改变像素的方法

c - 具有外部获取函数的未解析的外部符号

c++ - 使用宏访问 C 中的结构成员名称

c++ - 如何使用类型名对结构进行前向声明?