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

时间:2017-07-30 11:40:17

标签: c type-conversion sizeof implicit-conversion string-literals

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

2 个答案:

答案 0 :(得分:8)

The string literal "a" has the type char[2]. You can imagine it like the following definition

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

sizeof( char[2] ) is equal to 2 because (The C standard, 6.5.3.4 The sizeof and alignof operators)

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.

A character constant in C indeed has the type int. So for example sizeof( 'a' ) is equal to sizeof( int ) and usually equal to 4.

But when an object of the type char is initialized by a character constant like this

char c = 'a';

an implicit narrowing conversion is applied.

答案 1 :(得分:2)

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

Your assumption is incorrect. The string literal "a" consists of 2 char ('a', '\0'), meaning it's size is sizeof(char)*2 which is 2, or better yet, sizeof(char[2]).

Quoting the standard (on string literals):

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.