What you're missing is the definition of a string, it has to be null-terminated, by definition.
Quoting C11, chapter §7.1.1, (emphasis mine)
A string is a contiguous sequence of characters terminated by and including the first null
character. [....]
In your case, for arraytwo,
- it's automatic storage, and not initialized explicitly.
- you did not null-terminate it manually.
So, technically, arraytwo is not a string.
In this usage, as an argument to %s format specifier, out of bound access happens in search of the null-terminator, which causes undefined behavior.
Also quoting chapter §7.21.6.1
s
If no l length modifier is present, the argument shall be a pointer to the initial
element of an array of character type.280) Characters from the array are
written up to (but not including) the terminating null character. [....]
Solution:
- Either initialize the array elements to
0, something like char arraytwo[3] = {0};
- Or, manually null terminate your array, like
arraytwo[2] = '\0';
before using the array as string.
arraytwo[2] = '\0'%smeans to print a null-terminated string ... not just two charactersprintfto know that you want it to print two characters? How do you think this is going to work?