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

Jai*_*esh -4 c sizeof type-conversion string-literals implicit-conversion

/**** 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

2
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 8

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

char string_literal[] = { 'a', '\0' };
Run Code Online (Sandbox Code Playgroud)

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

4当sizeof应用于具有char,unsigned char或signed char(或其限定版本)类型的操作数时,结果为1.

C中的字符常量确实具有类型int.因此,例如sizeof( 'a' )等于sizeof( int )并且通常等于4.

但是当类型的对象char被像这样的字符常量初始化时

char c = 'a';
Run Code Online (Sandbox Code Playgroud)

应用隐式缩小转换.