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.