今天在看剑指offer里面的28题,字符串的排列,把书上的程序敲到VC里面加个main函数老是运行有错误,具体程序如下:
#include<iostream>
using namespace std;
void Permutation(char *pstr,char *pbegin);
void Permutation(char *pstr)
{
if(pstr==NULL)
return;
Permutation(pstr,pstr);
}
void Permutation(char *pstr,char *pbegin)
{
if(*pbegin=='\0')
cout<<pstr<<endl;
else
{
for(char *pch=pbegin;*pch!='\0';pch++)
{
char tmp=*pch;
*pch=*pbegin;
*pbegin=tmp;
Permutation(pstr,pbegin+1);
tmp=*pch;
*pch=*pbegin;
*pbegin=tmp;
}
}
}
int main()
{
char *str="abc";
Permutation(str);
return 0;
}
问题就出在这个main函数里面,char *pstr="abc",在网上查了一下,pstr是在栈上的,而"abc"是在常量区,静态存储区,是只读的不可写。
如果用char str[]="abc",就是可读,可写的;并且如果用char *p,然后p=malloc()来申请一块内存,也是可读可写的。