Reputation: 325
While reading about printing strings, I came through a statement "printf
writes the character one by one untill it encounters a null character. If the null character is missing, printf
continues past the end of the string until-eventually-it finds a null character in the memory". So I wrote some codes:
Case 1:
char arr[4] = { 'a', 'b', 'c' } ;
if (arr[3]== '\0')
printf ("%s",arr);
Output was abc
.
So does it mean compiler has automatically stored '\0'
at arr[3]
. Because according to the statement, printf will only terminate when it encounters '\0'
.
Case 2:
char arr[3] = { 'a', 'b', 'c' } ;
if (arr[3]== '\0')
printf ("%s",arr);
Output was abc
again though there is no array block arr[3]
in existence, so why isn't that an error? Also printf has printed abc
and stopped which means it must have encountered '\0'
. So does that mean compiler creates an extra array block after arr[2]
to store '\0'
.If so then array size must be increased to 4 bytes (1 byte for each char type character). But executing the statement printf ("%d",sizeof (arr));
gives me output 3
, showing that there is no increase in array size and indicating that there is no arr[3]
. Then how does the condition if (arr[3]== '\0')
became true?
Case 3:
char arr[3] = "abc";
if (arr[3]== '\0')
printf ("%s",arr);
Now it gives me an error saying that "array index 3 is past the end (which contains 3 elements)". So why isn't this same with case 2. Does that mean that declarations:
char arr[3] = "abc";
and
char arr[3] = { 'a', 'b', 'c' } ;
are different.
Upvotes: 5
Views: 976
Reputation: 409136
If the size of an array is larger than the number of elements you explicitly initialize, then the remaining elements will be zero-initialized.
So you can have e.g.
char arr[50] = { 'a' };
The first element (arr[0]
) will be initialized to contain 'a'
, the remaining 49 elements will all be zero.
Also note that when you define an array of three elements (like in the second two examples in your question) and then use arr[3]== '\0'
you are indexing out of bounds and have undefined behavior.
Furthermore, the contents of memory not inside your array is indeterminate. You can't rely on it being any value.
And lastly,
char arr[3] = "abc";
and
char arr[3] = { 'a', 'b', 'c' };
are actually the same, both create an array of three elements with the contents 'a'
, 'b'
and 'c'
.
Upvotes: 2