-1

What happens to the last (nth) character of a n-character string when I try to output the string?

I've included my code, sample input and output below that highlights that the last character I input is lost.

Code:

char buffer[10];
fgets(buffer, sizeof(buffer), stdin);
printf("%s", buffer);
return 0;

Input:

aaaaaaaaab (that's 9 a's followed by 1 b)

Output:

aaaaaaaaa (9 a's)

anastaciu
  • 23,467
  • 7
  • 28
  • 53
alexandrosangeli
  • 262
  • 2
  • 13
  • 5
    An *array* holds exactly the size it is defined for. On the other hand, the *string* in C is defined as an array terminated by a special `'\0'` character, which is taking up space. `fgets` is aware of this and is reserving one character for it. – Eugene Sh. Feb 16 '21 at 20:47
  • Does the "problem" lie when I output the string or when I ask for input? – alexandrosangeli Feb 16 '21 at 20:48
  • 3
    `fgets` will automatically terminate the string based on the size provided. When you are printing it it will print up to the null character. – Eugene Sh. Feb 16 '21 at 20:49
  • Thanks for that @EugeneSh. – alexandrosangeli Feb 16 '21 at 20:59

1 Answers1

2

For an array of characters to be treated as a propper string, its last character must be a null terminator (or null byte) '\0'.

The fgets function, in particular always makes sure that this character is added to the char array, so for a size argument of 10 it stores the first 9 caracters in the array and a null byte in the last available space, if the input is larger than or equal to 9.

Be aware that the unread characters, like b in your sample case, will remain in the input buffer stdin, and can disrupt future input reads.

This null byte acts as a sentinel, and is used by functions like printf to know where the string ends, needless to say that this character is not printable.

If you pass a non null terminated array of characters to printf this will amount to undefined behavior.

Many other functions in the standard library (and others) rely on this to work properly so it's imperative that you make sure that all your strings are properly null terminated.

anastaciu
  • 23,467
  • 7
  • 28
  • 53