The simple thing to do is to add a width specifier to your format string e.g
However, if you enter a name with spaces in it e.g. "James Earl Jones", then using the
format, scanf will read this as 3 separate words, not as a single line. Better would be to use a negative scanset
. In this case we are interested in any characters up to a newline. We can tell scanf to do that, with a field with, using
. Now scanf will read all characters in the input string, ending when either it has read 32 chars or finds a '\n'. But we still have an issue. If the name is over 32 chars, then the remaining characters are left in the input buffer waiting to be read on the next scanf. We don't want that! Additionally, unlike using
the terminating newline is not read, and the next scanf will return an empty string (actually, it does not modify the target variable at all), so we need to remove the newline before we can proceed. That actually helps us, since after the scanf, we just need to do a tight loop to read in any remaining characters up to and including the newline e.g.
}while(c !=' \n');
We still have a problem, though. We are allocating space for a name of 32 chars, and then reading in 32 chars. Given a long enough input string (32 or more characters), we actually overflow the string buffer we've allocated, since scanf adds a nul ('\0') to the end of the string. We need to either read in only 31 chars, or allow for the fact that we want to read in 32 chars, and so allocate string buffers of length 31.
Also, don't forget that when you call
, it only free's the block of memory associated with
name = (char **) malloc(count * sizeof(char*))
. This means that memory allocate for each individual name is no longer accessible (i.e. there is a memory leak). In this case, its not a serious problem, as the memory will be reclaimed when the program exits. But to properly clean up you should call
on each member of the
you free the array itself.