Since a C character array requires a null terminator, the following code prints four a s and some garbage characters.
char y[4] = {'a', 'a', 'a', 'a'};
printf("y = %s\n", y);
Output:
y = aaaa�
However, the following code produces no garbage characters.
char y[4] = {'a', 'a', 'a', 'a'};
char z[4] = {'b', 'b', 'b'};
printf("y = %s\n", y);
printf("z = %s\n", z);
Output:
y = aaaa
z = bbb
I understand that the fourth character of z
is automatically initialized with a null terminator. Also I guess that y
and z
get allocated next to each other in the memory.
But how does C correctly print just 4 a s in this case and not in the former? Does it identify that the next byte is already allocated to another variable, so it should stop printing anymore?