c-无法获取位域的地址 [英] c - cannot take address of bit-field

查看:746
本文介绍了c-无法获取位域的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能获取位域的地址?

如何创建指向位域的指针?

这是代码...

struct bitfield {
    unsigned int a: 1;
    unsigned int b: 1;
    unsigned int c: 1;
    unsigned int d: 1;
};

int main(void)
{
    struct bitfield pipe = {
        .a = 1, .b = 0,
        .c = 0, .d = 0
    };
    printf("%d %d %d %d\n", pipe.a,
            pipe.b, pipe.c, pipe.d);
    printf("%p\n", &pipe.a); /* OPPS HERE */
    // error: cannot take address of bit-field ...
    return 0;
}

推荐答案

位域成员(通常)小于指针允许的粒度,即指针char s的粒度(通过 definition char的值,顺便说一下,它至少必须为8位长.因此,常规指针不会削减它.

Bitfields members are (typically) smaller than the granularity allowed by pointers, which is the granularity of chars (by definition of char, which by the way is mandated to be 8 bit long at least). So, a regular pointer doesn't cut it.

此外,还不清楚指向位域成员的指针的类型是什么,因为要存储/检索这样的成员,编译器必须准确知道它在位域中的位置(并且没有常规"指针类型可以携带此类信息.

Also, it wouldn't be clear what would be the type of a pointer to a bitfield member, since to store/retrieve such a member the compiler must know exactly where it is located in the bitfield (and no "regular" pointer type can carry such information).

最后,这几乎不是必需的功能(位域通常不会出现在首位);位域用于紧凑地存储信息或构建标志的打包表示形式(例如,写入硬件端口),很少需要指向它们的单个字段的指针-如果需要,您总是可以使用常规的struct并在最后一刻转换为位域.

Finally, it's hardly a requested feature (bitfields aren't seen often in first place); bitfields are used to store information compactly or to build a packed representation of flags (e.g. to write to hardware ports), it's rare that you need a pointer to a single field of them - and if it's needed, you can always resort to a regular struct and convert to bitfield at the last moment.

由于所有这些原因,该标准规定位域成员不可寻址. 可以克服这些障碍(例如,通过定义特殊的指针类型来存储访问位域成员所需的所有信息),但这将是该语言又一个过于复杂的黑暗角落,没人使用

For all these reasons, the standard says that bitfields members aren't addressable, period. It could be possible to overcome these obstacles (e.g. by defining special pointer types that store all the information needed to access a bitfield member), but it would be yet another overcomplicated dark corner of the language that nobody uses.

这篇关于c-无法获取位域的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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