研究我试图解决此任务的指针
int main()
{
char buf1[100] = "Hello";
char buf2[100] = "World";
char *ptr1 = buf1+2;
char *ptr2 = buf2+3;
strcpy(ptr1, buf2);
strcpy(ptr2, buf1);
cout << ptr1 << endl << ptr2 << endl;
return 0;
}
尝试在不寻找答案的情况下解决:
世界
他的世界
就个人而言,我无法解决。我仅意识到前几个步骤:
char buf1[100] = "Hello";
char buf2[100] = "World";
ptr1
指针,它将以两个单位指示buf1
偏移量的地址。为了清楚起见,我们删除了buf1
的两个字符,并看到ptr1
指向单词l
中的第一个字母Hello
。char *ptr1 = buf1+2;
buf2
的前三个字符中划掉,然后看到指针ptr2
指向单词l
中的字母World
。char *ptr2 = buf2+3;
strcpy
函数正在复制。我不知道在什么地方复制了什么。 最佳答案
初始内存内容为:
buf1 buf2
v v
Hello World
^ ^
ptr1 ptr2
strcpy
函数将其第二个参数复制到第一个参数中。 strcpy(ptr1, buf2)
将buf2
(“世界”)的内容复制到ptr1
中。现在我们有了:buf1 buf2
v v
HeWorld World
^ ^
ptr1 ptr2
strcpy(ptr2, buf1)
将buf1
(“HeWorld”)的内容复制到ptr2
中。结果是:buf1 buf2
v v
HeWorld WorHeWorld
^ ^
ptr1 ptr2
因此,最后,
ptr1
指向字符串“World”,而ptr2
指向字符串“HeWorld”。