为什么这段代码的输出是
1234567890asdfg
asdfg
(我不能使用字符串类)
#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->a, test->b);
return 0;
}
最佳答案
您放入 test->a
的字符串长度为 11 个字符,包括终止空字符:1234567890\0
。当您将它复制到 a
时,该空字符将出现在 b
的第一个字符中。然后用复制到 b
中的字符串覆盖它,以便在内存中有:
a - - - - - - - - - b - - - - - - - - - - - - - - - - - - -
1 2 3 4 5 6 7 8 9 0 a s d f g \0
^
|
a's terminating null was here.
然后打印 a
(从 '1'
开始)和 b
(从 'a'
),生成该输出。
关于c - 具有多个字符数组问题的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4354491/