-4
/**** Program to find the sizeof string literal ****/ 

#include<stdio.h> 

int main(void) 
{ 
printf("%d\n",sizeof("a")); 
/***The string literal here consist of a character and null character, 
    so in memory the ascii values of both the characters (0 and 97) will be 
    stored respectively which are found to be in integer datatype each 
    occupying 4 bytes. why is the compiler returning me 2 bytes instead of 8 bytes?***/ 

return 0; 
} 

输出:我是c编程的初学者,需要sizeof()字符串常量的帮助吗?

2 
+2

“char”是一个1字节的整数类型。 –

+0

它由一个字符和一个空字符组成? – Jaivvignesh

+0

字符串文字具有“char”数组类型,并在内存中表示为以空字符结尾的字符数组。 –

回答

8

字符串文字"a"的类型为char[2]。你可以把它想象像下面的定义

char string_literal[] = { 'a', '\0' }; 

sizeof(char[2])等于2因为(C标准,6.5.3.4 sizeof运算和alignof运营商)

4当的sizeof被施加到操作数已键入字符型,无符号 炭,或符号的字符,(或者它们的合格版本)的结果是 1.

在C I的字符常量ndeed的类型为int。因此,例如sizeof('a')等于sizeof(int),通常等于4

但当类型char的一个目的是通过一个字符常数这样

char c = 'a'; 

初始化的隐式收缩转换被应用。

2

...将被分别存储,其被发现是在整数数据类型,每个占用4个字节

你的假设是不正确。字符串文字"a"由2个char'a', '\0')组成,意思是它的尺寸是sizeof(char)*2,它是2或更好,sizeof(char[2])

引用的标准(在字符串文字):

在翻译阶段7中,零值字节或码被附加到从字符串产生字面每个多字节字符序列或literals.78)的然后使用多字节字符序列来初始化静态存储持续时间和长度的阵列,其刚好足以包含该序列。对于字符串文字,数组元素的类型为char,并且使用多字节字符序列的各个字节进行初始化。

+0

printf(%d \ n“,sizeof('a'));/**正在返回我4字节**/ – Jaivvignesh

+1

@Jaivvignesh参见Vlad From Moscow的回答 – CIsForCookies