什麼是字符*海峽之間的區別使用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