簡體   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