有匿名结构声明符合法的ANSI C? [英] Are anonymous struct declarators legal in Ansi C?

查看:97
本文介绍了有匿名结构声明符合法的ANSI C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为是这样的转换是合法的(其中foo是一个无效指针):

I assume something like this cast is legal (where foo is a pointer to 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;

但我不知道是否该结构是的的定义是这样的是否是合法的:

But I'm wondering if the struct is not defined whether something like this is legal :

((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;

...或东西沿着这些路线。

... or something along these lines.

谢谢!

推荐答案

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

Yes, C allows casting to anonymous structures. Here is a quick demo:

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

这篇关于有匿名结构声明符合法的ANSI C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆