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

I am a beginner in programming in c,need help in sizeof() string constant?

/**** 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;
}

输出:

2

... will be stored respectively which are found to be in integer datatype each occupying 4 bytes

您的假设不正确。字符串文字 "a" 由 2 char ('a', '[=12=]') 组成,这意味着它的大小是 sizeof(char)*2,即 2,或者更好的是,sizeof(char[2]).

引用标准(关于字符串文字):

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence.

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

char string_literal[] = { 'a', '[=10=]' };

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

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

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

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

char c = 'a';

应用隐式缩小转换。