2

我假设像这样的演员是合法的(其中 foo 是指向 void 的指针):

struct on_off {
                  unsigned light : 1;
                  unsigned toaster : 1;
                  int count;            /* 4 bytes */
                  unsigned ac : 4;
                  unsigned : 4;
                  unsigned clock : 1;
                  unsigned : 0;
                  unsigned flag : 1;
                 };

((on_off) foo).count = 3;

但我想知道结构是否没有定义这样的东西是否合法:

((struct {
                  unsigned light : 1;
                  unsigned toaster : 1;
                  int count;            /* 4 bytes */
                  unsigned ac : 4;
                  unsigned : 4;
                  unsigned clock : 1;
                  unsigned : 0;
                  unsigned flag : 1;
         }) foo).count = 3;

...或类似的东西。

谢谢!

4

1 回答 1

3

是的,C 允许强制转换为匿名结构。这是一个快速演示:

struct xxx {
    int a;
};
...
// Declare a "real"struct, and assign its field
struct xxx x;
x.a = 123;
// Cast a pointer of 'x' to void*
void *y = &x;
// Access a field of 'x' by casting to an anonymous struct
int b = ((struct {int a;}*)y)->a;
printf("%d\n", b); // Prints 123

ideone 上的演示

于 2013-07-23T02:17:55.583 回答