我正在编写一个非常简单的测试程序来交换 char* 指向的字符串中的所有字符。但是,我从 Visual C++ 中得到了一个非常奇怪的异常。
我的代码会贴在下面,Chapter1 是项目的名称。
在此先感谢大家,如有任何其他问题,请随时在下方发帖。
问题2.h
#ifndef _QUESTION2_H_
#define _QUESTION2_H_
namespace Q2
{
void swap(char *begin, char *end);
void reverse(char *str);
void run();
}
#endif
问题2.cpp
#include <iostream>
#include "Question2.h"
using namespace std;
namespace Q2
{
void swap(char *begin, char *end)
{
char tmp = *begin;
*begin = *end;
*end = tmp;
}
void reverse(char *str)
{
char *begin = str;
char *end = str;
while(*end != NULL)
end++;
end--;
for(; begin < end; begin++, end--)
swap(begin, end);
}
void run()
{
char *str1 = "hello";
reverse(str1);
cout << str1 << endl;
return;
}
}
主要.cpp
#include <iostream>
#include "Question2.h"
int main()
{
Q2::run();
return 0;
}
最佳答案
声明:
char *str1 = "hello";
创建一个指向字符串文字(常量)的指针。您不能写入缓冲区(交换函数试图这样做),否则会导致未定义的行为。如果你真的想使用 C 风格的字符串,那么你可以将它声明为:
char str1[] = "hello";
通过该声明,它在堆栈上创建存储并将空终止字符串复制到该数组中;它仍然是一个以 null 结尾的字符串。
从正确性的角度来看,还有一件事:找到字符串结尾的循环应该与 '\0'
而不是 NULL 进行比较:
while(*end != '\0')
关于c++ - Chapter1.exe : 0xC0000005: Access violation writing location 0x0038EE7C 中 0x003860EF 处的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18646902/