struct的代码如何工作,请在下面解释代码 [英] How the code of struct works,Please explain the code below

查看:49
本文介绍了struct的代码如何工作,请在下面解释代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

运行的修改后的代码

Modified code which runs

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.


这是一种特殊的结构,称为位域.
整个结构存储在一个单词中,冒号后面的数字表示每个元素占用了该单词的多少位.因此,"a"是3位(包括0-7),"b"是3位,而"c"是2位(包括0-3).复杂的是int是有符号类型,因此您的值范围要小得多...
您的代码无法编译,因此没有必要详细解释!首先修复语法错误,然后询问特定问题.
This is a special kind of struct, called a bitfield.
The whole structure is stored in a single word, with the number after the colon indicating how many bits of that word are taken by each element. So "a" is 3 bits (0-7 inclusive), "b" is 3 bits, and "c" is 2 bits (0-3 inclusive). The added complication is that int is a signed type, so your value range is a lot smaller...
Your code won''t compile, so there is no point in explaining it in detail! Fix your syntax errors first, then ask about specific problems.


struct abc
{
int a:3;
int b:3;
int c:2;
}


在结构abc中定义(请注意:缺少的分号是语法错误)三个位字段.全部共享相同的类型,即有符号整数ab的长​​度为三位(它们可以保存值{-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的代码如何工作,请在下面解释代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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