结构标签

CHR*_*RIS 4 c label struct

CI希望能够在结构中标记特定位置.例如:

struct test {
    char name[20];

    position:
    int x;
    int y;
};
Run Code Online (Sandbox Code Playgroud)

这样我就能做到:

struct test srs[2];
memcpy(&srs[1].position, &srs[0].position, sizeof(test) - offsetof(test, position));
Run Code Online (Sandbox Code Playgroud)

将srs [0]的位置复制到srs [1]中.

我已经尝试将位置声明为没有任何字节的类型但是这也不起作用:

struct test {
    char name[20];

    void position; //unsigned position: 0; doesn't work either
    int x;
    int y;
};
Run Code Online (Sandbox Code Playgroud)

我知道我可以将x和y嵌入另一个名为position的结构中:

struct test {
    char name[20];

    struct {
        int x;
        int y;
    } position;
};
Run Code Online (Sandbox Code Playgroud)

或者只使用x属性的位置:

struct test srs[2];
memcpy(&srs[1].x, &srs[0].x, sizeof(test) - offsetof(test, x));
Run Code Online (Sandbox Code Playgroud)

但是我想知道是否有办法做我最初提出的建议.

小智 9

struct test {
    char name[20];

    char position[0];
    int x;
    int y;
};
Run Code Online (Sandbox Code Playgroud)

0长度数组在网络协议代码中非常流行.

  • +1,很好的例子,应该添加它不是C而是GNU扩展. (4认同)

oua*_*uah 5

另一个使用 C11 匿名联合和匿名结构的解决方案:

struct test {
    char name[20];

    union {
        int position;
        struct {
            int x;
            int y;
        };
    };
};
Run Code Online (Sandbox Code Playgroud)

的地址position是member之后的下一个结构成员的地址name

我显示它只是为了显示它,因为自然的解决方案是仅x在问题的第一个结构声明中获取成员的地址。