Reputation: 468
My question is about the sizeof
operator in C.
sizeof('a');
equals 4, as it will take 'a'
as an integer: 97.
sizeof("a");
equals 2: why? Also (int)("a")
will give some garbage value. Why?
Upvotes: 5
Views: 1595
Reputation: 59607
'a'
is a character constant - of type int
in standard C - and represents a single character. "a"
is a different sort of thing: it's a string literal, and is actually made up of two characters: a
and a terminating null character.
A string literal is an array of char
, with enough space to hold each character in the string and the terminating null character. Because sizeof(char)
is 1
, and because a string literal is an array, sizeof("stringliteral")
will return the number of character elements in the string literal including the terminating null character.
That 'a'
is an int
instead of a char
is a quirk of standard C, and explains why sizeof('a') == 4
: it's because sizeof('a') == sizeof(int)
. This is not the case in C++, where sizeof('a') == sizeof(char)
.
Upvotes: 23
Reputation: 7686
because 'a' is a character, while "a" is a string consisting of the 'a' character followed by a null.
Upvotes: 4