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?
'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)
.
because 'a' is a character, while "a" is a string consisting of the 'a' character followed by a null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With