c - Ansi C 中的匿名结构声明符是否合法?

标签 c

我认为这样的转换是合法的(其中 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;

...或类似的东西。

谢谢!

最佳答案

是的,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

Demo on ideone .

关于c - Ansi C 中的匿名结构声明符是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17800410/

相关文章:

c - nlopt 中的固定区间约束

C编程: malloc() inside another function

c - 在 C 中将多维数组作为参数传递给函数

c++ - 如何同时从多个线程访问 MySQL

c - 在 Solaris 上构建 Node.JS : "Use of <stdbool.h> is valid only in a c99 compilation environment."

c - 关于结构的基本问题

c - vl_ubcmatch 在技术上是如何工作的?

c - 错误的文件描述符 fileno

c - 为什么这个 char Array(C 语言) 打印超过它的容量?

c - 阶乘的时间复杂度