连接两个字符串(K& R)

时间:2013-06-04 22:09:43

标签: c

我正在尝试模仿K& R中给出的示例程序,如下所示:

void strcat(char s[], char t[])
{
    int i, j;
    i = j = 0;
    while (s[i] != '\0') /* find end of s */
        i++;
    while ((s[i++] = t[j++]) != '\0') /* copy t */
        ;
}

我想做同样的事情,除了将t添加到s之外,我想将两者都复制到一个新字符串中。我的尝试如下:

#include <stdio.h>
#include <string.h>

void concat
(const char lstr[], const char rstr[], char outstr[])
{
    int i, j;

    i = j = 0;
    while (lstr[i] != '\0')
        outstr[i++] = lstr[i++];
    while ((outstr[i++] = rstr[j++]) != '\0')
        ;
}

int main(void)
{
    char lword[] = "foo";
    char rword[] = "bar";
    char outword[strlen(lword) + strlen(rword)];

    concat(lword, rword, outword);
    printf("%s\n", outword);
}

但是,上面只打印垃圾(我的意思是f�����bar)。我无法找出错误所在。

3 个答案:

答案 0 :(得分:3)

两个问题:

  • outword中没有空格来终止空字符。需要:

    char outword[strlen(lword) + strlen(rword) + 1];
                                             /*^^^*/
    
  • 这是undefined behaviour因为i在同一声明中被修改了两次:

    outstr[i++] = lstr[i++];
    
    /* Change to: */
    
    while (lstr[i] != '\0')
    {
        outstr[i] = lstr[i];
        ++i;
    }
    

通过这两个更改,程序会生成一个新的连接字符串(http://ideone.com/9QbU0q)。

答案 1 :(得分:3)

C中的每个字符串都需要以空字符结尾,该字符将不可见。但是,它确实需要考虑你分配的内存大小。

答案 2 :(得分:0)

lstr复制到outstr时,您的索引会递增两次。使用outstr[i] = lstr[i++]

相关问题