【问题标题】:Why output of the below code is -1 and -2? [duplicate]为什么下面代码的输出是-1和-2? [复制]
【发布时间】:2017-05-10 10:27:52
【问题描述】:

为什么下面代码的输出是-1和-2,应该是1和2吧?

同样在 64 位服务器上,以下结构的大小是 4 字节,应该是 8 字节吧?

#include<stdio.h>
struct st
{
        int a:1;
        int b:2;
};
main()
{
        struct st obj={1,2};
        printf("a = %d\nb = %d\n",obj.a,obj.b);
        printf("Size of struct = %d\n",sizeof(obj));
}

【问题讨论】:

  • 你得到的答案是-1 and -2-1 and 2?
  • @SouravGhosh -1 和 -2 先生
  • "应该是 1 和 2,对吧?"不,你为什么认为它应该是这样的?

标签: c struct bit-fields


【解决方案1】:

在启用所有警告的情况下进行编译,并阅读编译器的内容:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
main.c:7:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main()
^
main.c:9:26: warning: implicit truncation from 'int' to bitfield changes value
      from 2 to -2 [-Wbitfield-constant-conversion]
        struct st obj={1,2};
                         ^
main.c:11:40: warning: format specifies type 'int' but the argument has type
      'unsigned long' [-Wformat]
        printf("Size of struct = %d\n",sizeof(obj));
                                 ~~    ^~~~~~~~~~~
                                 %lu
3 warnings generated.

回想一下,

一个有符号的 1 位变量只能保存两个值,-1 和 0

正如您在answer 中看到的那样。

所以如果你改用这个结构:

struct st
{
        int a:2;
        int b:3;
};

你会得到想要的输出。


answer 也给出了很好的解释。

【讨论】:

  • 不客气@Chirag,我用一个工作结构更新了我的答案,希望这足以接受! :)
  • 是的,我很清楚这个概念,感谢您的帮助
猜你喜欢
  • 2022-11-27
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-01
  • 2019-01-09
相关资源
最近更新 更多