简体   繁体   English

分段错误:倒车时的字符串

[英]Segmentation fault error : While reversing a string

#include<stdio.h>
#include<string.h>
void reverseMe(char *,int,int);
int main()
{
  char str[]="cycle";
  int len=strlen(str);
  reverseMe(str,0,len-1);
  return 0;
}

void reverseMe(char *x,int begin,int end)
{
  char c;
  c=*(x+begin);
  *(x+begin)=*(x+end);
  *(x+end)=c;

  reverseMe(x,++begin,--end);
}

Why do I get segmentation error? 为什么会出现细分错误? What is the error I have made? 我犯了什么错误?

Huh? ??

You never check against the limits of the string, reverseMe() does infinite recursion. 您永远不会检查字符串的限制, reverseMe()会进行无限递归。 Of course it's going to give your fireworks. 当然会给你烟花。

You should have something like 你应该有这样的东西

if(begin < end)
{
  const char c = x[begin];
  x[begin] = x[end];
  x[end] = c;
  reverseMe(x, begin + 1, end - 1);
}

inside reverseme() . 内部reverseme() Also note that array indexing is clearer than pointer arithmetic, in many cases. 还要注意,在许多情况下,数组索引比指针算法更清晰。

Your function is invalid because there is no condition to exit the function (recursion). 您的函数无效,因为没有条件可以退出该函数(递归)。

Try the following 尝试以下

void reverseMe( char *s, int begin, int end )
{
   if ( begin < end )
   {
      char c =  s[begin];
      s[begin] = s[end];
      s[end] = c;
      reverseMe( s, begin + 1, end - 1 );
   }
}

Also as this function deals with strings then I would define it the following way 另外,由于此函数处理字符串,因此我将通过以下方式定义它

char * reverseMe( char *s, int begin, int end )
{
   if ( begin < end )
   {
      char c =  s[begin];
      s[begin] = s[end];
      s[end] = c;
      return reverseMe( s, begin + 1, end - 1 );
   }

   return s;
}

In this case you could use it the following way 在这种情况下,您可以按以下方式使用它

char str[] = "cycle";
printf( "%s\n", reverseMe( str, 0, strlen( str ) - 1 ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM