Reputation: 115
I couldn't exactly explain my question well in the title. Here are two sets of code:
int main() {
char str[81] = "Hello World";
scanf("%s", str);
str[3] = 'X';
printf("%s", str);
return 0;
}
When entering 789, the output is "789Xo World", which shows that the scanf function is replacing the first 3 indices of the char array with the input and the str[3] line replaces the 4th with 'X'. This makes sense to me.
int main() {
char str[81] = "Hello World";
scanf("%s", str);
printf("%s", str);
return 0;
}
When inputting 789, this outputs 789. Scanf is no longer replacing the first 3 indices of str, but rather the whole thing. It confuses me that manually changing the 4th index (str[3]) would somehow make the program change the front of str instead of replacing it entirely?
I'm very new to C and I can't find an explanation anywhere in my textbook. Thanks ahead of time for your help.
Upvotes: 2
Views: 80
Reputation: 672
A String in C is composed by many char plus a \0 [end of string/null terminator] char at the end. When you are assigning Hello World to the str array you get something like this:
[H][e][l][l][o][ ][W][o][r][l][d][\0]
So when you call scanf and write 789 this happens to your array:
[7][8][9][\0][o][ ][W][o][r][l][d][\0]
Then you change the str[3] (4th position in the array) with X but with that assignment you're overwriting the end of string character, this happens:
[7][8][9][X][o][ ][W][o][r][l][d][\0]
so the next printf call will print everything until he reach \0 that's why you got 789Xo World on screen. In your second example, when you type 789 after calling scanf, you're leaving the string like this
[7][8][9][\0][o][ ][W][o][r][l][d][\0]
printf will stop at the first \0 and you get 789.
Upvotes: 7