数组越界问题

来源:百度知道 编辑:UC知道 时间:2024/06/03 18:42:42
函数功能是实现将以字符串倒转,中间出了一个我无法理解的错误:见注释

#include<iostream>
#include <assert.h>
using namespace std;

char *HeadToEnd(char * pStore)
{
assert(pStore != NULL);
char *pTmp = pStore;
int len = strlen(pStore);
if(len <= 1)
{
return pTmp;
}
else
{
char tmp;
for(int i=0; i<len/2; i++)
{
tmp = pStore[i];
pStore[i] = pStore[len-i-1]; //运行时出错,段错误,求达人解释
pStore[len-i-1] = tmp;
}
return pTmp;
}

}

int main()
{
char j[10] = {0};
strcpy(j,HeadToEnd("abcdef"));
cout<<j<<endl;
system("pause");
return 0;
}
程序就是执行到这一句就出错,我实在想不出来哪里错了,望指教!!

问题在这里
strcpy(j,HeadToEnd("abcdef"));

"abcdef"这个字符串是保存在常量区的,是不允许修改的,而你的HeadToEnd直接指向这个常量,并修改之,当然出错。

改成这样吧
char j[] = "abcdef";
//char *j = "abcdef"; 注意这行也不行的,照样会出现那个错误
HeadToEnd(j);

pStore[i] = pStore[len-i-1];
这句话本身没有什么问题
你再查查别的地方有没有错误