【问题标题】:Copy contents of one array to another with pointers使用指针将一个数组的内容复制到另一个数组
【发布时间】:2015-04-24 04:07:00
【问题描述】:

我自学 C++ 已经有一段时间了,但在指针方面我遇到了“障碍”。我将其用作我的http://www.cplusplus.com/doc/tutorial/pointers/ 学习材料,但我仍然遇到问题。所以为了测试一些东西,我想将一个数组的内容复制到另一个数组中。我写了以下内容。

char arrayA[15] = "abcdef";
char arrayB[15];

char *a = arrayA;
char *b = arrayB;

cout << "before loop:" << endl;
cout << a << endl;
cout << b << endl;

while (*a != '\0') {
    // Copy the contents of a into b
    *b = *a;

    // Step
    a++;
    b++;
}

// Assign null to the end of arrayB
*b = '\0';

cout << "after loop:" << endl;
cout << a << endl;
cout << b << endl;

我得到以下结果。

before loop:
abcdef

after loop:

当我 cout 循环之前的内容时,我得到了预期的结果。 a 包含 "abcdef" 而b 什么都不是,因为还没有任何值。现在在循环之后,ab 都没有显示任何结果。这就是我迷路的地方。我使用* 取消引用ab 并将a 的值分配给b。我哪里做错了?我需要使用&amp; 吗?

解决方案:

循环完成后,指针*a指向arrayA的末尾,指针*b指向arrayB的末尾。因此,要获得 arrayB 的完整结果,只需 cout &lt;&lt; arrayB。或者创建一个永不改变的指针,在循环结束时始终指向数组B char *c = arrayBcout &lt;&lt; c

【问题讨论】:

  • 注意NULL不是空字符,写成'\0'。 NULL 是一个 C 宏,表示一个空指针,不应该在 C++ 中使用(对于指针,使用新的文字 nullptr,或者简单地为 0)。
  • @Peter Schneider 谢谢。进行了必要的更改。
  • 哦,不要使用未初始化的数组,例如用于输出(例如“beforeLoop”之后的arrayB)。在第一个 char 中写入 '\0' 使其变为空字符串。您的程序只是巧合地工作(除非数组是全局的,在这种情况下它们被归零)。

标签: c++


【解决方案1】:

循环ab 发生变化后,它们指向字符串的末尾。您需要复制要逐步执行的指针,以便在迭代时不会更改 ab 的位置。

【讨论】:

    【解决方案2】:

    问题是您正在输出用于遍历数组的临时变量。它们现在位于复制数据的末尾。您应该输出 arrayAarrayB 的值。

    【讨论】:

    • 感谢您的意见。我很感激。
    【解决方案3】:

    记住数组的开头。在这一刻,您正在递增指针并在循环结束后打印它们在数组末尾指向的内容。

    char arrayA[15] = "abcdef";
    char arrayB[15];
    
    char *a_beg = arrayA;
    char *b_beg = arrayB;
    char *a;
    char *b;
    
    cout << "before loop:" << endl;
    cout << a_beg << endl;
    cout << b_beg << endl;
    
    a = a_beg;
    b = b_beg;
    while (*a != '\0') {
        // copy contents of a into b and increment
        *b++ = *a++;
    }
    // assign null to the end of arrayB
    *b = '\0';
    
    cout << "after loop:" << endl;
    cout << a_beg << endl;
    cout << b_beg << endl;
    

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多