繁体   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);
}

为什么会出现细分错误? 我犯了什么错误?

??

您永远不会检查字符串的限制, reverseMe()会进行无限递归。 当然会给你烟花。

你应该有这样的东西

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

内部reverseme() 还要注意,在许多情况下,数组索引比指针算法更清晰。

您的函数无效,因为没有条件可以退出该函数(递归)。

尝试以下

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 );
   }
}

另外,由于此函数处理字符串,因此我将通过以下方式定义它

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;
}

在这种情况下,您可以按以下方式使用它

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