I am following Kernighan and Ritchie's C book but I'm having some difficulties working with strings.
In the following code, it appears that my strings, while inputted from the user via getchar()
contain additional, what I would say are junk characters, before the null (\0
) character.
Here is the code:
#include <stdio.h>
main() {
char s[200];
int c, i;
printf("Enter input string:\n");
for (i = 0; ( c = getchar()) != '\n'; i++) {
s[i] = c;
}
printf("Contents of input string:\n");
for (i = 0; s[i] != '\0'; i++) {
printf("%d: (%d) = ", i, s[i]);
putchar(s[i]);
printf("\n");
}
return 0;
}
And here's the output showing each element of the character array one by one. It means the following:
Array_element: (ascii_number) = ascii_character
0: (72) = H
1: (101) = e
2: (108) = l
3: (108) = l
4: (111) = o
5: (32) =
6: (87) = W
7: (111) = o
8: (114) = r
9: (108) = l
10: (100) = d
11: (33) = !
12: (-1) = ?
13: (127) =
Ya see elements 12 and 13? (element 14 is presumably the null character \0
). Whiskey. Tango. Foxtrot.
And here's the real kicker, if I define the character array to have only 100 elements, not 200, the output is reasonable. For example, if I simply replace
char s[200]
with
char s[100]
then the output is as follows:
0: (72) = H
1: (101) = e
2: (108) = l
3: (108) = l
4: (111) = o
5: (32) =
6: (87) = W
7: (111) = o
8: (114) = r
9: (108) = l
10: (100) = d
11: (33) = !
12: (9) =
(I'm still not sure where the newline character is. Isn't that ascii character # 10?)
Again, whiskey tango foxtrot.
What is going on here?
Update
So as per the answers below, it would appear the difference in output between when I set my character array to be 100 or 200 elements in size is really coincidence - I am just playing with garbage/noise in uninitialized memory.
I need to explicitly terminate my array with \0
as the answers astutely indicate.
In this exercise if you expect the null character to exist in the string after the input, then you'll need to add it yourself.
You're observing odd characters because variables and arrays in C come uninitialized: they can contain any garbage values, possibly including randomly placed null characters.
You may observe different output when you change around array sizes, but don't expect any reasonable, expected or repeatable behavior - it's undefined - because those array values can be anything.