某公司的笔试题如下
已知如下代码, 求输出结果.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
char arr_a[4];
char arr_b[32];
};
int main()
{
struct Test a1;
strcpy(a1.arr_b,"hello world");
strcpy(a1.arr_a,"hello");
printf("%s\n",a1.arr_b);
system("pause");
return 0;
}
代码strcpy(a1.arr_a, "hello") 将*(a1.arr_a + 4)赋值为'o', 将*(a1.arr_a + 5)赋值为'\0', 而a1.arr_a + 4即为a1.arr_b, a1.arr_a + 5即为a1.arr_b + 1, 故输出结果为: o
------------------------------------------------------以上为转载内容-------------------------------------------------
------------------------------------------------------以下为原创内容-------------------------------------------------
更直接的解释是,因为arr_a只能存四个字符,而“hello”这个字符串却要占用6个字符(包括'\0'),所以a1.arr_a只能被赋值为hell,由于struct成员的内存连续性,a1.arr_a中剩余的o\0只能覆盖a1.arr_b的部分内容,所以a1.arr_b的内容由原来的hello world\0就变为现在的o\0llo world\0,由于字符串是由\0作为结束标志的,因此结果就为单单一个字母o