How can I use a variable to specify the max number of chars scanf()
should read in?
For example using printf()
you can use the * like so
You can't. You need to use something other than scanf()
. A good and popular choice is fgets()
, although its semantics are slightly different: fgets()
will read a line of input, whereas scanf()
with %s
will read whitespace separated sequences of characters.
To use fgets()
, you'd want something like:
fgets(string, MAXVAL, stdin);
If for some reason you really want to use scanf()
, have a look at this question: How to prevent scanf causing a buffer overflow in C?