什么是字符*海峡之间的区别使用malloc时或没有?
int i;
char *s = (char*)malloc(sizeof(char)*27);
for(i=0;i<26;i++)
s[i]='a'+i;
s[26]='\0';
printf("%s\n",s);
reverse(s);
printf("%s\n",s);
其中反向()是
void reverse(char *str)
{
int i,j=strlen(str)-1;
char tmp;
for(i=0;i<j;i++,j--)
{
tmp=str[i];
str[i]=str[j];
str[j]=tmp;
}
}
这工作得很好,但在使用
char *t = "new string";
printf("%s\n",t);
reverse(t);
printf("%s\n",t);
我得到一个段错误和调试器说,这是在strlen的反向。将char * t更改为char t []可以正常工作。是什么赋予了?
Duplicates:http://stackoverflow.com/questions/2124600/how-to-reverse-a-string-in-place-in-c-using-pointers http://stackoverflow.com/questions/480555/修改c字符串常量http://stackoverflow.com/questions/1011455/is-it-possible-to-modify-a-string-of-char-in-c http://stackoverflow.com/questions/ 164194/why-does-simple-c-code-receive-segmentation-fault – nos