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
将数据添加到缓冲区。