简体   繁体   English

结构 - 解释输出:

[英]Struct - Explain the output:

I have the following C code. 我有以下C代码。

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

void main(){
  struct values v={2,-6,5};
  printf("%d %d %d",v.a,v.b,v.c); 
}

When I execute the code, I am getting the following output: 当我执行代码时,我得到以下输出:

2 2 1.

But output should be 2 -6 5 , right? 但输出应该是2 -6 5 ,对吗?

If I'm wrong please explain. 如果我错了请解释。

-6 exceeds the range of a 3-bit signed int. -6超出了3位signed int的范围。 Therefore you're observing an artifact of undefined implementation-defined behaviour (in practice, the most-significant bits of your value are being thrown away). 因此,您正在观察未定义的实现定义行为的工件(实际上,您的值的最重要部分将被丢弃)。

{2,             |  -6,             |        5        }
010 last 3 bits |  010 last 3 bits |  01 last 2 bits
2                  2                        1    

No. Output is 2 2 1 . 不。输出是2 2 1

The C compiler converts the values to Binary, and stores in the memory. C编译器将值转换为Binary,并存储在内存中。

Binary value of 2 : 00000010 二进制值2: 00000010

Binary value of -6: 11111010 (11111001+1) 二进制值-6: 11111010 (11111001 + 1)

Binary value of 5 : 00000101 二进制值为5: 00000101

While storing in memory: 存储在内存中:

For 2, 010 will be stored. 对于2,将存储010。

For -6, 010 will be stored. 对于-6,将存储010。

For 5, 01 will be stored. 对于5,将存储01。

When you access these variables from your main method, for va "010" will be returned, here left most bit is for sign. 当您从main方法访问这些变量时,对于va将返回“010”,此处最左侧的位用于符号。

So va is 2. Similarly vb is 2 and vc is 1. 所以va是2.类似地,vb是2,vc是1。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM