具有多个char数组问题的struct

1 c arrays struct

为什么输出此代码

1234567890asdfg
asdfg
Run Code Online (Sandbox Code Playgroud)

(我不能使用字符串类)

#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;
}
Run Code Online (Sandbox Code Playgroud)

Cas*_*bel 6

你输入的字符串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.
Run Code Online (Sandbox Code Playgroud)

然后打印a(从开始'1')和b(从中开始'a'),生成该输出.