EXC_BAD_ACCESS 发生在 *str++ = *end;
。这有什么问题吗?
#include <iostream>
using namespace std;
int main() {
char *hello = "abcdefgh";
char c = 'c';
char *str = hello;
//printf("%s",str);
char * end = str;
char tmp;
if (str) {
while (*end) {
++end;
}
--end;
while (str < end) {
tmp = *str;
printf("hello:%s str:%c, end:%c\n", hello, *str, *end);
*str++ = *end;
*end-- = tmp;
}
}
return 0;
}
最佳答案
尝试更改字符串文字是未定义的行为。将您的代码更改为以下等效代码,您将看到问题:
const char *hello = "abcdefgh";
const char *str = hello;
const char * end = str;
那么你明白为什么行 *str++ = *end;
有问题了吗?您正在尝试写入 const
区域,但您不能这样做。
如果你想要一个更简单的例子:
int main()
{
char *str = "abc";
str[0] = 'x';
}
如果这个简单的程序在
str[0] = 'x';
行被执行。
不幸的是,字符串文字不必在 C
中声明为 const char*
,而 C++
带来了这种语法。因此,即使看起来您没有使用const
,但您确实在使用。
如果您希望代码真正起作用,请声明一个可写缓冲区,即一个 array
字符:
char hello[] = "abcdefgh";
char str[100];
strcpy(str, hello);
char end[100];
strcpy(end, str);
关于c++ - EXC_BAD_ACCESS 在用指针分配 char 时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723371/