0

For example, does this code allow for the maximum size string that this array could store to be entered? (255 characters of input from scanf, and then leaving room for a null terminator to be added)

char string[256]
scanf("%255s", string);

Or does the scanf function automatically add the null terminator to the end of the input meaning that in order to allow for 255 characters plus a null terminator I would want to specify a width of 256 in the scanf function, like so?

char string[256]
scanf("%256s", string);

Any help would be appreciated, and this is my first question on S/O so if I have done something wrong please let me know! :)

Shane1470
  • 71
  • 5
  • 2
    You use `scanf` wrong in both cases. First of all it doesn't [return](https://en.cppreference.com/w/c/io/fscanf#Return_value) what you think it does. Secondly it does add the null-terminator, but it can't extend the array in any way. So reading 256 character *plus* the terminator will write the terminator out of bounds. – Some programmer dude Oct 28 '21 at 16:41
  • 2
    Does this answer your question? [Read no more than size of string with scanf()](https://stackoverflow.com/questions/12306591/read-no-more-than-size-of-string-with-scanf) – Mark Benningfield Oct 28 '21 at 16:45
  • 1
    The length limit is the number of actual characters read from the input, it doesn't include the null terminator. – Barmar Oct 28 '21 at 16:45
  • 1
    The first version is correct, the second is wrong. – Barmar Oct 28 '21 at 16:45

0 Answers0