sizeof
gives the size of its operand. To understand the results you are seeing, you need to understand what pass1
, pass2
, pass3
, and pass4
actually are.
pass1
is a pointer to char (i.e. a char *
) so sizeof pass1
gives the size of a pointer (a variable which contains a memory address, not an array). That is 8
with your compiler. The size of a pointer is implementation defined, so this may give different results with different compilers. The fact you have initialised pass1
so it points at the first character of a string literal "abc"
does not change the fact that pass1
is declared as a pointer, not an array.
pass2
is an array initialised using the literal "abc"
which - by convention - is represented in C using an array of four characters (the three letters 'a'
to 'c'
, plus an additional character with value zero ('\0'
).
pass3
is also an array of four char
, since it is declared that way char pass3[4] = <etc>
. If you had done char pass3[4] = "abcdef"
, you would still find that sizeof pass3
is 4
(and the 4 elements of pass3
will be 'a'
to 'd'
(with other character 'e'
, 'f'
, and '\0'
in the string literal "abcdef"
not used to initialise pass3
).
Since both pass2
and pass3
are arrays of four characters, their size is 4 (in general, the size of an array is the size of the array element multiplied by number of elements). The standard defines sizeof char
to be 1
, and 1*4
has a value 4
.
pass4
is initialised using the literal ""
. That string literal is represented using a single char with value '\0'
(and no characters before it, since none are between the double quotes). So pass4
has size 1
for the same reason that pass2
has size 4.