问题描述
struct abc
{
int a:3;
int b:3;
int c:2;
}
void main()
{
struct abc a=(2,3,4)
printf(" %d %d %d",a.a,a.b,a.c);
gethc();
}
推荐答案
struct abc
{
int a:3;
int b:3;
int c:2;
};
int _tmain(int argc, _TCHAR* argv[])
{
struct abc a = {2,3,4};
printf(" %d %d %d, %d",a.a,a.b,a.c,sizeof(struct abc));
return 0;
}
因此,在您的结构中,这里a被分配了3位,b被分配了3位,c被分配了2位.现在,当您将值赋予结构变量时.
位中提供的值
a = 10(二进制为2)(从三分之二中占用2位空间)
b = 11(二进制为3)(在三分之二内占用2位空间)
c = 100(二进制为4)(需要3位空间,但只有2位)
因此a和b的值将正确打印,但是c的值将为0,因为不会存储(100)中的第三位,即1.
So here a is assigned 3 bits, b is assigned 3 bits and c is assigned 2 bits in your structure. Now when you give value to a structure variable.
Values provided in bit
a = 10 (2 in binary) (take 2 bit space out of three)
b = 11 (3 in binary) (take 2 bit space out of three)
c = 100 (4 in binary) (needs 3 bit space but have 2 bit only)
so value of a and b will be printed correctly, but value of c will be 0, as third bit from (100) that is 1 is not stored.
struct abc
{
int a:3;
int b:3;
int c:2;
}
在结构abc
中定义(请注意:缺少的分号是语法错误)三个位字段.全部共享相同的类型,即有符号整数,a
和b
的长度为三位(它们可以保存值{-4,-3,-2,-1,0,1,2,3}
),而c
的长度为两位(可以保留值)值{-2,-1,0,1}
).
Defines (note: the missing semicolon is a syntax error) three bit fields in the struct abc
. All share the same type, namely signed integer, a
and b
are three bits long (they may hold the values {-4,-3,-2,-1,0,1,2,3}
) while c
is two bits long (it may hold the values {-2,-1,0,1}
).
struct abc a=(2,3,4)
上一行(再次,缺少的分号是语法错误)通过以下方式初始化结构abc
的实例a
:
The above line (again, the missing semicolon is a syntax error) initializes the instance a
of the struct abc
this way:
a.a = 2;
a.b = 3;
a.c = 4; // NOTE: 4 is an out of range value for c
printf(" %d %d %d",a.a,a.b,a.c);
上面的行显示了位字段的值.
The above line prints the values of the bit fields.
gethc();
我不知道那是什么您是说getch();
吗?
I don''t know what it is. Do you mean getch();
instead?
这篇关于struct的代码如何工作,请在下面解释代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!