I am trying to understand something basic about how 'strings' are defined in c.
printf("sizeof s %d", sizeof(s));
%s conversion specification tells
printf to print the sequence of characters starting at the specified address until it sees the 0 terminator at the end of the string. Similarly, it tells
scanf to store a sequence of characters starting at the specified address until it sees a whitespace character or EOF.
When you pass the expression
s as an argument to
printf, the expression is converted from type "2-element array of
char" to "pointer to
char", and the value of the expression is the address of the first element of the array (it's equivalent to passing the expression
scanf receives is a pointer value - it has no idea how big the array starting at that address is. So it doesn't know that
s is only large enough to contain two characters. Instead, it happily writes those extra characters past the end of the array. Similarly,
printf doesn't know that the array is only 2 characters wide - it just keeps printing until it sees that 0 terminator.
You can specify a field width as part of the conversion:
scanf( "%1s", s );
This will read at most 1 character from standard input and store it to
s. Remember that a string is a sequence of characters followed by a 0 terminator, so to store an N-character string, you need to set aside an N+1-element array to store it.