研究我试图解决此任务的指针

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;
}

尝试在不寻找答案的情况下解决:

世界
他的世界

就个人而言,我无法解决。我仅意识到前几个步骤:
  • 声明一个100个单位的char型数组。数组由文本初始化。
    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”。

    10-06 01:59