写一个函数reverse(s)的递归版本,它将字符串s反转到位。我似乎无法找到错误

时间:2013-07-21 10:07:40

标签: c string recursion

这是来自K和R的问题。当我尝试编译它时,它说分段错误(核心转储)。我似乎无法找到错误。

#include <stdio.h>

这是你的基本交换

 void swap(char s[], int i, int j) {
    char temp;
    temp = s[i];
    s[i] = s[j];
    s[j] = temp;
}


void reverse(char s[]){
    int i, j;

    if (i == 0) 
        j = strlen(s)-1;
    swap(s, i, j);
    j--;
    i++;
    // Here is where the problem arises. When i don't call the function here the program works perfectly  (The limitation being only the first and last char get swapped) otherwise it gives an error saying segmentation fault
    if (i < j)
        reverse(s);
}

int main () {
    int i;
    char s[10] = "hello";
    reverse(s);
    printf("%s", s);
}

3 个答案:

答案 0 :(得分:1)

首先,当您在i内声明reverse时,您没有为其指定值,因此其值将是随机的。因此,当您在比较中使用i时,它是未定义的行为。

答案 1 :(得分:0)

ij在函数反转时未初始化。

执行此操作时:

if (i==0)

您正在将未初始化的变量与零进行比较,因此j也未被初始化。

即使你反向初始化它们也不会有效,因为reverse是递归调用的。

假设您反向初始化ij,如下所示:

void reverse (char s[])
{
 int i = 0, j = strlen(s)-1;
   .....
   ...
 reverse(s);
}

因为每次你通过i&amp;时都会递归调用它。 j交换它们再次初始化 到0strlen(s)-1,所以最好在main()中初始化它们,然后按照下面给出的方式将它们传递给它。

我认为你最好尝试这样的事情:

void reverse(char s[], int i, int j)
{
  swap( s , i , j);
  --j;
  i++;
  if (i < j)
    reverse( s , i , j);
}

然后在main()中执行类似的操作:

  char s[] = "hello";
  int i = 0 , j = strlen(s)-1;
  reverse( s , i , j);
  printf("%s" , s);

答案 2 :(得分:0)

交换功能

 void swap(char *s, int i, int j)

{
    char temp;
    temp = s[i];
    s[i] = s[j];
    s[j] = temp;
    printf("swap %s\n",s);
}

反向功能

void reverse(char *s,int j,int i)

这里我传递地址所以 s和j我必须从main中获取,因为我们无法初始化此反向函数中的变量,因为它可能会导致终止条件出现问题。你犯了同样的错误。< / em>的

{
    printf("%d\t%d\n",i,j);
    if(i<j)//`base condition`
{
    swap(s, i, j);
    reverse(s,--j,++i);
}
}

- j将在j和++中递减i我将在i中递增。其中preincrement和predecrement是关键

主要功能

    int main ()
{
    int i=0;
    char s[10] = "hello";
    printf("%s\n",s);
    reverse(s,(strlen(s)-1),i);
    printf("%s\n", s);
    return 0;
}

<强>输出

hello
0   4
swap oellh
1   3
swap olleh
2   2
olleh