之间&QUOT差; 3英寸和'3'用C [英] Difference between "3" and '3' in C

查看:104
本文介绍了之间&QUOT差; 3英寸和'3'用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行在C下面的程序,并得到了一些输出。你能帮助我,为什么???

I tried to run the following program in C and got some output. Can you help me out why???

#include<stdio.h>

int main()
{
  char x='A';
  printf("%d%d%d",sizeof("3"),sizeof('3'),sizeof(3));
  return 0;
}

收到的输出为2 4 4在Ubuntu 11.04 32位使用gcc。

The output received is 2 4 4 using gcc in ubuntu 11.04 32 bit.

同样,在其他程序: -

Similarly in other program:-

#include<stdio.h>

int main()
{
  char x='A';
  printf("%d%d",sizeof('A'),sizeof(x));
  return 0;
}

在Ubuntu中使用GCC收到的输出为4 1 32 11.04位。

The output received is 4 1 using GCC in ubuntu 11.04 32 bit.

您能帮我为什么输出是这样???

Can you help me out why the output is this way???

推荐答案

在C,字符文字是整数类型,因此的sizeof(' 3')==的sizeof(INT)。详情请参阅此Ç常见问题解答

In C, char literals are of integer type, so sizeof('3') == sizeof(int). See this C FAQ for details.

这就是C和C ++不同(在C ++领域之一的sizeof('3') 1 )。

This is one of the areas where C and C++ differ (in C++ sizeof('3') is 1).

其实,纠正我的previous断言,的sizeof(3),因为3为2元字符数组处理会产生2

Actually, correcting my previous assertion, sizeof("3") will yield 2 because "3" is treated as a 2-element character array.

6.3.2.1/3

6.3.2.1/3

除了当它是sizeof操作符的操作数或一元
  &安培;运营商,或者是用于初始化数组文本字符串,
  具有类型'类型的阵列'前pression被转换为
  前pression型指向最初的指针键入''
  该数组对象和元素不是左值。

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

这篇关于之间&QUOT差; 3英寸和'3'用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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