【问题标题】:Issues when trying to copy one char array to another (without using already existing functions)尝试将一个 char 数组复制到另一个时出现问题(不使用现有函数)
【发布时间】:2023-03-09 20:15:01
【问题描述】:

我目前坚持将一个 char 数组复制到另一个 char 数组。当我尝试这样做时,我最终切断了一个数组的大部分并收到“ed”。结果是我的 arr2[] 的最后 3 个字符。我不允许使用内置函数,所以我试图从头开始,但我面临着提到的问题。有什么建议吗?

#include <iostream>
#include "Print.h"


using namespace std;

void Copy(char arr1[], char arr2[]);

int main(){

    char arr1[] = {"Hello how are you? \0 hiii"};
    char arr2[] = { "The weather was cloudy today, so it rained. \0" };
    char arr3[] = { "Coffee is a great way to start the day. \0" };

    Print(arr1);

    Copy(arr2, arr3);

}
void Copy(char cloud[], char coffee[]){

        while (*coffee != '\0')
        {
            *cloud = *coffee++;
            ++cloud;
        }

        cout << cloud << endl;

}

【问题讨论】:

  • 对于我程序中的另一个函数,它不涉及问题,它打印出一个数组。我专注于尝试让我的 Copy() 函数工作。
  • 您可能需要在复制后添加一个额外的'\0' 来终止字符串。但是,您正在做的事情很危险且容易出错。
  • 在循环的末尾,cloud 指向末尾,所以cout &lt;&lt; cloud 没有用处
  • 源和目标等有意义的变量名也会更有用。

标签: c++ function char


【解决方案1】:

当我尝试这样做时,我最终会切断一个数组的大部分内容并收到“ed”。结果

发生这种情况是因为您正在递增 Copy 中的两个变量,并且您不是 null 终止 cloud

我的建议:使用数组索引来复制数组。

void Copy(char cloud[], char coffee[])
{
   int i = 0;
   while ( coffee[i] != '\0' )
   {
      cloud[i] = coffee[i];
      ++i;
   }

   // Make sure to null terminate cloud
   cloud[i] = '\0';

   // This should produce the expected output.
   cout << cloud << endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2021-04-15
    • 2023-02-08
    相关资源
    最近更新 更多