Confused with the char array when scanf
I am confused with one tiny program.
#include <stdio.h>
#define LEN 10
int main()
{
char str1[LEN] = "\0";
char str2[LEN] = "\0";
scanf("%s", str1);
scanf("%s", str2);
printf("%s\n", str1);
printf("%s\n", str2);
return 0;
}
If my input are:
mangobatao
ma开发者_开发技巧ngobatao123456
Why should the output be:
123456
mangobatao123456
And not:
mangobatao
mangobatao123456
How has the char
array has been allocated in the memory?
Well, a 10 character char
array won't fit "mangobatao"
, since it has 10 characters - there's no room for the null terminator. That means you've caused undefined behaviour, so anything could happen.
In this case, it looks like your compiler has laid out str2
before str1
in memory, so when you call scanf
to fill str2
, the longer string overwrites the beginning of str1
. That's why you see the end of what you think should be in str2
when trying to print str1
. Your example will work fine if you use a length of 100.
I think your compiler has allocated space for str2[10] just 10 characters before the str1 pointer.
Now, when you scanf a string of length 16 at str2, the string terminator '\0' is appended at str2 + 17th position, which is infact str1 + 7.
Now when you call printf at str1, the characters read are actually str2 + 11, str2 + 12,..., str2 + 16 until the null terminator is encountered at str2 + 17 (or str1 + 7). The printf at str2 must be obvious.
精彩评论