2011-11-26 96 views
-3

可能重复:
Modifying C string constants?字符串差异

什么是字符*海峡之间的区别使用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 []可以正常工作。是什么赋予了?

+2

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

回答

5

这是正常的:

char * t = "new string"; 

t指向一个字符串。修改它会导致未定义的行为,并且大多数实现将这些文字存储在只读内存部分中。在你的情况下,你有一个段错误,但有时它会看起来像它的工作。

char *s = (char*)malloc(sizeof(char)*27); 

这分配了一块新的内存。既然那段记忆属于你,你可以随心所欲地做。

+0

为什么不只是'char xxx [27]'?为什么'sizeof(char)'?它总是1. – 2011-11-26 00:06:36

+0

@Vlad不要问我,我个人会抛弃C并使用C++的'std :: string'。 –

+0

C++不是一个选项,谢谢你的信息 – Mike