C++ 带指针的任务

C++ 带指针的任务,c++,pointers,C++,Pointers,为了研究指针,我试图解决这项任务 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 << en

为了研究指针,我试图解决这项任务

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;
}
intmain()
{
char buf1[100]=“你好”;
char buf2[100]=“世界”;
char*ptr1=buf1+2;
char*ptr2=buf2+3;
strcpy(ptr1,buf2);
strcpy(ptr2,buf1);

cout初始记忆内容为:

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”。

正如您提到的,您知道
ptr1
指向
llo
ptr2
指向
ld

现在查看第一个strcpy

strcpy(ptr1, buf2);  
这将把
World
复制到
buf1
ptr1
指向的地方,因此它实际上现在指向
World
。因此打印
ptr1
将打印
World

由于
buf1
(衰变后)和
ptr1
分别指向世界字符串的
Hello
l
的不同元素(
l
),对
ptr1
所做的任何修改都将反映到
buf1
。因此,
buf1[]
现在变成
HeWorld

由于原始字符串已被修改,因此
ptr2
不再指向
l
。现在它指向字符串
HeWorld的
W

现在请参见第二个strcpy

 strcpy(ptr2, buf1);  

<> P>现在这将开始代码> HeWorths/Cuth>从代码> PtR2< /Co> >点。因此打印<代码> PTR2<代码>打印<代码> HeWorths。< /P>决定您是否正在学习C或C++。(<代码> cOUT/CODE>建议C++)您读过<代码>
?在将字符串设置为字符指针时,不需要指定大小。因此
char buf1[]=“Hello”
char buf2[]=“World”;
是“正确”的方法。@valter这里的方法可能是错误的,因为代码使用
strcpy
将数据添加到缓冲区。