【发布时间】:2014-07-21 23:59:14
【问题描述】:
我正在尝试反转一个字符串,
不知道为什么我会得到以下错误Unhandled exception at 0x00f818c2 in CPP_TEST.exe: 0xC0000005: Access violation writing location 0x00f87838.?
请帮帮我。
void swap(char* in, int start, int end)
{
char *temp = new char;
*temp = in[start];
in[start] = in[end];//Unhandled exception at 0x00f818c2 in CPP_TEST.exe: 0xC0000005: Access violation writing location 0x00f87838.
in[end] = *temp;
}
void Reverse(char* in, int start, int end)
{
if(start == end)
{
cout << in <<endl;
return;
}
else
{
while(start != end)
{
swap(in, start++, end--);
//Reverse(in, start, end);
}
}
}
int main()
{
char* in = "Hello";
Reverse(in, 0, 4);
system("pause");
return 0;
}
【问题讨论】:
-
in指向字符串文字。你不能修改它。另外,swap中存在内存泄漏。 -
通常情况下,至少会使用
std::swap,如果不是std::reverse。也没有这些错误。无论如何,指向字符串文字的char *在 C++ 中已被弃用(您应该收到编译器警告,如果不这样做,请打开/打开它们)并且在 C++11 中是非法的。
标签: c++