c - 段错误错误: While reversing a string

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

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

最佳答案

嗯?

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

你应该有类似的东西

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

reverseme()内。另请注意,在许多情况下,数组索引比指针算术更清晰。

关于c - 段错误错误: While reversing a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24633719/

相关文章:

c++ - 应用程序在编译错误后执行时关闭,但在调试时它工作正常!

c - 在宏中输出注释

c - 代码是否可以在两家不同公司生产的 Cortex A5 和 Cortex A9 之间轻松移植?

谁能解释一下程序的输出?

c++ - 为什么此代码会导致 SIGSEGV(gcc 编译器、cygwin 下的 Android NDK 工具链)?

python - 导入时pyqt5段错误

c++ - 简单的 OpenGL 代码总是导致段错误(Ubuntu 上的 C++,虚拟机)

c++ - 将节点附加到链表时出现段错误

C变量分配时间和空间

c - 将数据放入 .text 时会出现汇编器警告和 gcc 警告