将字符串连接到指针变量的末尾

Concatenate a string onto the end of a pointer variable

C 的新手。在使用某个函数时遇到问题。该函数假设将一个 str 连接到 *destp 的末尾。首先通过调用 kstrextend() 将 *destp 扩展到足以容纳两个字符串的内容。然后将src的内容复制到dest中。

这是我当前的代码,只是因为它可以编译。我想进行更改,以便可以调用重新分配内存的 kstrextend() 函数。 我也是 运行 测试用例,在它要求 "kstrcat of two empty kstrings."

之后我有一个核心转储
    void kstrcat(kstring *destp, kstring src)
    {
        int lenDest = destp->length;
        //int lenSrc = src.length;

       destp = realloc(destp,lenDest*sizeof(char));

       int i = 0;

       while(src.data[i] != '[=10=]')
       {
           destp->data[i+lenDest+1] = src.data[i];
       }
       destp->data[i+lenDest+1] = '[=10=]';
   }

这里还有我的 kstrextend 函数,以供参考或我可能需要更改的任何内容。

    void kstrextend(kstring *strp, size_t nbytes)
    {
        char *data1;
        int len=strp->length;
        if(len < nbytes)
        {
            //allocate a new array with larger size
            data1 = realloc(strp->data, nbytes);
            if(data1 == NULL)
            {
                abort();
            }
            strp->data = data1;
            strp->length = nbytes;
            //remaining space of new array is filled with '[=11=]'
            for (int i = len; i < nbytes; i++)
            {
                strp->data[i] = '[=11=]';
            }
       }
   }

这就是连接两个字符串的方式

char *strcat(char *dest, char *src)
{
    char *pend;

    /* make pend point to end of dest */
    for (pend = dest; *pend; ++pend)
        ;

    /* copy src to pend. Assume dest has enough space */
    while (*pend++ = *src++)
        ;

    /* null terminate dest */
    *pend = 0;
    return dest;
}

分配给目标字符串时,您不应将索引加 1。这将在其中留下结束目标字符串的空字节,而不是用源的第一个字节覆盖它。

此外,您忘记在循环中递增 i

void kstrcat(kstring *destp, kstring src)
{
    int lenDest = destp->length;
    int lenSrc = src.length;

    kstrextend(destp, lenDest + lenSrc);

    int i = 0;
    while(src.data[i] != '[=10=]')
    {
        destp->data[i+lenDest] = src.data[i];
        i++;
    }
    destp->data[i+lenDest] = '[=10=]';
}