为什么这个联合体的大小是2和位字段? [英] Why this union's size is 2 with bitfields?

查看:189
本文介绍了为什么这个联合体的大小是2和位字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows上的Turbo C的工作,其中焦炭需要一个byte.Now我的问题是下面的结合。

I am working on turbo C on windows where char takes one byte.Now my problem is with the below union.

union a
{
 unsigned char c:2;
}b;
void main()
{
printf("%d",sizeof(b));  \\or even sizeof(union a)
}

此程序是打印输出2,其中作为工会应该只服用1个字节。为什么会这样呢?

有关结构它是好的给予1个字节,但这个工会工作不当。

还有一的事情如何访问这些位域。

This program is printing output as 2 where as union should be taking only 1 byte. Why is it so?

for struct it is fine giving 1 byte but this union is working inappropriately.

And one more thing how to access these bit fields.

scanf("%d",&b.c);  //even scanf("%x",b.c);

不工作,因为我们不能bits.So有地址,我们必须使用另一个变量像下面

is not working because we cannot have address for bits.So we have to use another variable like below

int x;
scanf("%d",&x);
b.c=x;

我们不能避免它?是否有任何其他方式?

cant we avoid it?? is there any other way???

推荐答案

<一个href=\"http://web.archive.org/web/20080627072007/http://cunion.blogspot.com/2008/01/why-we-cannot-use-relation-and-logical.html\"相对=nofollow> Turbo C的基于微处理器8086具有两个字节字边界。原子阅读和写作通常是必然CPU的架构,因此编译器中加入一些松弛字节对齐你的数据结构。

Turbo C is based on 8086 microprocessor which has two byte word boundary. The atomic reading and writing is typically bound to CPU's architecture, so the compiler is adding some slack bytes to align your data structure.

调用的#pragma包(1)也许可以禁用它,但不知道它的工作原理上的Turbo C。

Calling #pragma pack(1) may be able to disable it, but not sure if it works on Turbo C.

这篇关于为什么这个联合体的大小是2和位字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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