struct with multiple char arrays problem
Why is output of this code
1234567890asdfg
asdfg
(i can't use string class)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct S
{
char a[10];
char b[20];
};
int main()
{
struct S* test = (S*)malloc(sizeof(S));
strcpy(test->a, "1234567890");
strcpy(test->b, "asdfg");
printf("%s\n%s", test->开发者_StackOverflow中文版;a, test->b);
return 0;
}
The string you've put in test->a
is eleven characters long including the terminating null character: 1234567890\0
. When you copy it into a
, that null character ends up in the first character of b
. You then overwrite it with the string you copy into b
, so that in memory you have:
a - - - - - - - - - b - - - - - - - - - - - - - - - - - - -
1 2 3 4 5 6 7 8 9 0 a s d f g \0
^
|
a's terminating null was here.
You then print a
(starting from the '1'
), and b
(starting from the 'a'
), producing that output.
The string "1234567890"
actually needs 11 byte (char
s).
So that you overwrite the first character of b
.
精彩评论