小编use*_*090的帖子

C++使用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 …
Run Code Online (Sandbox Code Playgroud)

c++ arrays string pointers char

0
推荐指数
1
解决办法
1169
查看次数

标签 统计

arrays ×1

c++ ×1

char ×1

pointers ×1

string ×1