Technically both cases invoke undefined behavior. That the first case happens to work on your system should not be taken to mean that your program is well-defined. Testing can only indicate the presence of bugs, not their absence.
Since you're still learning C I will take the opportunity to offer you advice for reading input from stdin
: always limit the length of input that will be read to the length of the buffer it's being read in to, reserving one spot at the end for the null-terminator.
If you want to use scanf
to read strings from stdin
, then it is safer to prefix the string format specifier with the maximum length of the string than to use a raw "%s"
. For example, if I had a char buffer[20];
that was the destination of a call to scanf
, I would use the format string "%19s"
.