从给定子集打印长度为k的字符串

时间:2014-12-30 04:09:49

标签: c string

尝试使用递归从给定输入中打印k长度集。 我想要的例子:

输入:

3
a b c

输出:

aaa
aab
aba
.
.

等等。

我以某种方式得到垃圾值!

int klength(char input[],char output[],int size, int k, int curr){
    int i=0;
    if(k<=0)
    {
    puts(output);
    return 0;
    }
    for(i=0;i<size;i++)
    {
        output[curr]=input[i]; // **EDIT**
        printf("current output %s\n",output);
        klength(input,output,size,k-1,++curr);
        printf(" after recursion %s]n,output);
    }
}

有人可以指出我的错误吗?!我无法以某种方式找到我的错误,而且我的运行时间有点短:\提前谢谢!

1 个答案:

答案 0 :(得分:3)

klength(input,output,size,k-1,++curr);

这里每次在循环中递增curr,这意味着它会快速增加并最终溢出输出缓冲区。你想要

klength(input,output,size,k-1,curr+1);

代替。