use*_*653 -1 c segmentation-fault
#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);
}
Run Code Online (Sandbox Code Playgroud)
为什么会出现分段错误?我犯的错误是什么?
咦?
你永远不会检查字符串的限制,reverseMe()无限递归.当然它会给你的烟花.
你应该有类似的东西
if(begin < end)
{
const char c = x[begin];
x[begin] = x[end];
x[end] = c;
reverseMe(x, begin + 1, end - 1);
}
Run Code Online (Sandbox Code Playgroud)
在里面reverseme().另请注意,在许多情况下,数组索引比指针算法更清晰.