c++ - 在不使用标准库和字符串的情况下连接 char*

标签 c++ pointers char

我需要实现一种方法,在不使用任何标准库(它是规范的一部分)的情况下将不同的字符连接到一个 char* 中。所以,没有 strcat 或 strcopy。我也不能使用字符串。

这是我尝试做的(字符存储在我自己实现的 StringList 中,因此有“GetCell”方法和 ->next 指针):

  char* IntlFinder::ConcatenateSrc ( int nSource, long beginPosition )
        char* res = new char;
        Cell* cell = ComList.GetCell(beginPosition);
        for (long i = beginPosition; i <= (CountTab[nSource]); i++)
        {
            if (nSource == 0 || cell->elem.source == nSource)
            {
                res[i-beginPosition] = cell->elem.caractere;
            }
            cell = cell->next;
        }

        *res = '\0';
        return res;
    }

当我调试时,这看起来很棒,直到我到达某个字符,然后它无缘无故地出现错误(当时它指向的单元格看起来很正常,具有有效地址)。

对此有什么想法吗?

--

编辑:我试着这样做:

    for (long i = beginPosition; i <= (CountTab[nSource]-1); i++)
    {
        if (nSource == 0 || cell->elem.source == nSource)
        {
            *res = cell->elem.caractere;
            ++res = new char;
        }
        cell = cell->next;
    }

应该增加指针并分配内存(这样我可以在下一次迭代中添加另一个值),并且我不再有任何 SIGSERV 错误。 但是当我返回指向第一个字符的这个指针或指针的原始值时,我什么也得不到(在第一种情况下)或只得到第一个字符(在第二种情况下)。

我没有忘记在末尾添加'\0',但这仍然不能使它成为一个字符串。

最佳答案

类似于:

char * concat(char dest[], char src[])
{
   int i = 0, j = 0;
   while (dest[i]) ++i;
   while (src[j]) dest[i++] = src[j++];
   dest[i] = '\0';
   return dest;
}

前提是dest 足够大,可以承载它的selt 和src。否则,可能会因为写到数组的边界之外而导致意想不到的结果。

添加

int main()
{
    char * buf = new char[1 << 30]; // allocate 2^30 = 1e9+ chars (very huge size)
    // you can use char buf[1 << 30];
    // which is faster and not needing to be released manually
    char tmp[] = "First portion";
    char tmp2[] = "Second porition";
    buf[0] = '\0'; // so that concat begins copying at 0
    concat(buf, tmp);
    // buf == "First portion"
    concat(buf, tmp2);
    // buf = "First portionSecond portion"

    ....
    // don't forget to release memory after you have finished
    delete[] buf;
    return 0;
}

关于c++ - 在不使用标准库和字符串的情况下连接 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12754496/

相关文章:

c - 无符号字符数组的输出

c++ - 如何将 ".bc"库中的符号(即 : . 来自 emar archiver builder 的后缀)导出到 javascript?

c++ - 您如何将变量外包给持久数据?

c - 尝试对 c 中的结构数组使用 realloc 导致无效指针

c - 通过引用将静态二维结构数组传递给函数

c - 打印存储为字符串的十六进制值会产生意外输出

c++ - 围绕另一个 3D 点旋转

C++ 17 std::filesystem 无法在其他(Windows 10)计算机上运行

c - 使用指针销毁双端队列并在 C 中释放

c++11 - 有没有办法在不修改缓冲区内容的情况下设置 std::string 的长度?