Actually, you are getting it wrong my brother. The initialization of str_arr
doesn't affect the working of scanf()
, it may however seem to you like that but it ain't actually. As described in other answers too this is called undefined behavior. An undefined behavior in C itself is very vaguely defined .
The C FAQ defines “undefined behavior” like this:
Anything at all can happen; the Standard imposes no requirements. The
program may fail to compile, or it may execute incorrectly (either
crashing or silently generating incorrect results), or it may
fortuitously do exactly what the programmer intended.
It basically means anything can happen. When you do it like this :
char *str;
scanf("%s",str);
Its an UB. Sometimes you get results which you are not supposed to and you think its working.That's where debuggers come in handy.Use them almost every time, especially in the beginning. Other recommendation w.r.t your program:
- Instead of
scanf()
use fgets()
to read strings. If you want to use scanf then use it like scanf("%ws",name);
where name is character array and w
is the field width.
- Compile using -Wall option to get all the warnings, if you would have used it, you might have got the
warning that you are using str uninitialized
.
Go on reading THIS ARTICLE, it has sufficient information to clear your doubts.