Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between sizeof('a') and sizeof("a")

Tags:

c

sizeof

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?

like image 354
Bharath Bhandarkar Avatar asked Sep 10 '12 18:09

Bharath Bhandarkar


2 Answers

'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).

like image 134
pb2q Avatar answered Sep 22 '22 13:09

pb2q


because 'a' is a character, while "a" is a string consisting of the 'a' character followed by a null.

like image 24
MJB Avatar answered Sep 26 '22 13:09

MJB