C++使用char*复制字符数组(无字符串库)

use*_*090 0 c++ arrays string pointers char

我正在编写一个C++函数,它应该通过将每个元素逐个字符复制到一个新数组来复制一个字符数组.理想情况下,如果我发表声明

char* a = "test";
char* b = copyString(a);
Run Code Online (Sandbox Code Playgroud)

那么a和b都应该包含字符串"test".但是,当我打印复制的数组b时,我得到"test"加上一系列似乎是指针的无意义字符.我不想要那些,但我无法弄清楚我哪里出错了.

我目前的功能如下:

char* copyString(char* s)
{
     //Find the length of the array.
    int n = stringLength(s);

    //The stringLength function simply calculates the length of 
    //the char* array parameter.

    //For each character that is not '\0', copy it into a new array.
    char* duplicate = new char[n];

    for (int j = 0; j < n; j++)
    {
        duplicate[j] = s[j];

        //Optional print statement for debugging.
         cout << duplicate[j] << endl;
    }

    //Return the new array.
    return duplicate;
}
Run Code Online (Sandbox Code Playgroud)

为了理解C++的某些方面,我不能使用字符串库,这是我发现的其他答案在这种情况下不足之处.非常感谢任何有关此问题的帮助.

编辑:我虽然我的stringLength函数很好 - 也许我错了.

int stringLength(char* s)
{
    int n;

    //Loop through each character in the array until the '\0' symbol is found. Calculate the length of the array.
    for (int i = 0; s[i] != '\0'; i++)
    {
        n = i + 1;
    }

    //Optional print statement for debugging.
    // cout << "The length of string " << s << " is " << n << " characters." << endl;

    return n;
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 6

你也需要复制0.这就是C风格的字符串,一个以null结尾的字符数组.

真的,你需要做的就是添加一个长度:

    int n = stringLength(s) + 1; // include the '\0'
Run Code Online (Sandbox Code Playgroud)

然后其他一切都会解释自己 - 你将分配一个足够大小的数组,并复制'\0'你的循环.