Quote:
Originally Posted by de4df1sh
how come despite only allocating 4 characters in the array, the program still prints names of +4 characters such as casey,zachary,roberto?
Welcome to C. Many functions in C will happily overflow the memory you've provided them, and that is what scanf is doing here. Sometimes it does what you've shown here, sometimes it does weirder things. For example, because you've written into memory space not owned by StudentName, it's possible that another variable owns that space and may write into it.
Quote:
If I change it so it is char studentname [3] it only prints cas, zac, rob, ect ect
If you change to to [3] it should have the same behavior as [4]. If it isn't doing that, then it's pure luck/happenstance. As I said above, the behavior is essentially undefined.
How do you fix it? Here's the really funny part - you really can't. There is no absolutely safe way to use %s with scanf.
If you must use %s with scanf, then the best way to do it is to read the data another way, say using getline() and then manually truncate the string before using sscanf() to be sure you won't overrun your variable. (sscanf is a variant of scanf that reads from a char array instead of a file handle)