【问题标题】:Concatenate strings recursively in C在C中递归地连接字符串
【发布时间】:2016-04-30 11:10:02
【问题描述】:

我需要帮助来使用 C 中的递归连接字符串。

我在输入中有 2 个字符串,srcdest,我需要将 src 递归连接到 dest ,并将连接的字符串存储在dest中。

例如如果 src="house"dest="clock" ,则输出应为 "chlooucske"

编辑:这是我的代码:

char* str_concatenate(char dest[], char src[], int index){
    char temp[256]; // temporaty variable
    temp[index]=src[index]; //should copy each letter from src to temp
    temp[index+1]=dest[index]; //should copy each letter from dest to temp
    dest[index]=temp[index]; //should store the concatenated string into dest
    if (src[index]=='\0'){ //base case
        return dest;
    }
    else
        return str_concatenate(dest,src,index+1);
}

int main(){ //test
        char dest[]="house";
        char src[]="clock";

        char* ris=str_concatenate(dest,src,0);

        printf("dest= %s\n", ris); //should print "chlooucske" 
    return 0;
    }

但是,它将整个单词从 src 复制到 dest 并打印出来,它不会连接字母。

【问题讨论】:

  • dest 指向字符串文字。不能修改字符串文字。需要分配一个可写缓冲区。例如:char dest[MAX_LEN] = "home";
  • 你如何期望这个函数永远返回除NULL-pointer之外的任何东西?你知道你不能将NULL 传递给printf(),对吧?
  • @marco2012,今天似乎每个人都对你很生气。他们正在投票给你,除了建设性的帮助外,他们提供了一切。看起来您的代码想要交错两个字符串?我没有看到串联发生。你有几个问题。一个是您每次递归输入函数时都分配一个新的临时数组。另一个是当你在 src[index] 找到一个空终止符时,你在基本情况下返回一个空指针。我建议您告诉我们您想要的结果是什么,其他人会帮助您实现目标。
  • malloc() 的使用会造成很大的内存泄漏。为什么不使用普通数组?
  • 我可以帮忙 - 使用你的调试器。

标签: c recursion concatenation


【解决方案1】:

目标指针指向一个字符串常量。您正在尝试修改它,它会导致您的程序崩溃。您可以使用数组并将其初始化为目标字符串。

您可能想看看这个。这解释了你的问题。 What is the difference between char s[] and char *s?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2017-10-28
    • 2012-11-16
    相关资源
    最近更新 更多