【问题标题】:How and is the output of my code is 842?我的代码的输出如何以及是 842?
【发布时间】:2015-06-13 11:20:52
【问题描述】:
#include <stdio.h>

int main(){
printf("%d\t",sizeof(6.5));
printf("%d\t",sizeof(90000));
printf("%d\t",sizeof('a'));

return 0;
}

当我编译我的代码时,输​​出将是:“842”。 有人可以解释为什么我会得到这个输出吗?

【问题讨论】:

  • 你期望什么输出?
  • 请注意,您的代码甚至无法按原样编译,这让我认为这不是您的实际代码。我也期望“8 4 1”,除非您的编译器启用了宽字符支持。
  • @PaulR:我希望最后一个数字是“4”,因为'a' (奇怪的是)是int 类型(而不是人们可能合理假设的char) ...
  • @RobertWalton 请复制并粘贴您的真实代码,而不是输入一些内容并弄错

标签: c sizeof 32-bit 16-bit


【解决方案1】:

首先是代码中的语法错误

printf("%d\t";sizeof('a')); 

把这个改成

printf("%zu\t",sizeof('a'));   //note the change in format specifier also
             ^
             |
            see here

那么,假设你的平台是 32 位的

  • sizeof(6.5) == sizeof(double) == 8
  • sizeof(90000) == sizeof(int) == 4
  • sizeof('a') == sizeof(int) == 4

为了澄清,a 表示 为 97,默认为 int。所以,sizeof('a') 的值应该是 4,而不是 2 或 1。


编辑:

添加,如果在 16 位架构中,您将获得 8 4 2 的输出

  • sizeof(6.5) == sizeof(double) == 8
  • sizeof(90000) == sizeof(long) == 4
  • sizeof('a') == sizeof(int) == 2

【讨论】:

  • int 的大小是实现定义的。它可能是 OP 系统上的2
  • @MattMcNabb 但它不应该改变,对吧?所以应该是822或者844,不可能是842吧?
  • @MattMcNabb 但是,添加了有关平台依赖性的注释。希望现在没事吧?
  • @DilipKumar 如果你在一个 2 字节 int 的平台上,90000 可能是 4 字节长。
  • @DilipKumar 可以是 842。90000 不适合 16 位类型,所以如果 int 是 16 位类型,那么 90000 将是 long,可能是诠释。
【解决方案2】:

如果您使用的是 32 位编译器

printf("%d\t",sizeof(6.5));

6.5 是双精度,所以sizeof(double) 给出8

printf("%d\t",sizeof(90000));

90000 是一个 int (或 long ),所以 sizeof(int) 给出 4

printf("%d\t";sizeof('a'));
             ^
             you left a semicolon here, change it to a comma

'a' 被转换为 int,所以sizeof(int) 给出了4

所以实际输出是

8     4      4

ideone link

但是,如果你使用的是 16 位编译器,你会得到

sizeof(6.5) = sizeof(double) = 8
sizeof(90000) = sizeof(long) = 4
sizeof('a') = sizeof(int) = 2

这样就可以解释你的输出了。

【讨论】:

  • 为什么不是 8 4 4 ??就目前而言,'a' == 97 == int
  • 确实char的大小应该是1,奇怪的是他的输出不一样
  • @CosminMihai 不。这不是char
  • may consider...你能详细说明一下吗?
  • "The compiler may consider 'a' as a char, int or long. " -> 不,可能不会。它是一个 int,在您的情况下为 4,尽管有些平台的 int 也不是 4 个字节。 (只要确保代码是用 C 编译器编译的,在 C++ 编译器中输出会有所不同)。
猜你喜欢
  • 2019-11-23
  • 2017-12-16
  • 1970-01-01
  • 2023-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
相关资源
最近更新 更多