String literals in C have types of character arrays that contain as many characters as explicitly specified in string literals plus the terminating zero.
For example string literal "a"
consists from two characters 'a'
and '\0'
and have type char [2]
.
In this definition of array str2
char str2[1]="a";
you explicitly specified that it size equal to 1. So sizeof( str2 )
will be equal to 1 that is number_of_characters * sizeof( char )
Take into account that such definition of str2
is considered as an invalid definition in C++ because there is more initializers than initialized objects (that is elements of type char) because as I pointed out above string literals contain the terminating zero.
In this array definition
char str3[]="a";
the size of the array is not specified so it is calculated based on how many initializers are used. As string literal contains two characters ( 'a'
and '\0
') then str3
will be initialized with these characters and will contain two elements. That is str3
will be an exact copy of the string literal. So sizeof( str3 )
will be equal to 2.