字符指针分配段故障

时间:2011-03-26 13:04:44

标签: c string segmentation-fault variable-assignment

#include <stdio.h>
#include <stdlib.h>
int main(){
 char *str="abcdce";
 char c='c';
 char *pfast=str,*pslow=str;
 while(*pfast!='\0'){
     if(*pfast==c){
       pfast++;
       *pslow=*pfast; //error here when pfast reaches the first 'c'
     }
    pfast++;
    pslow++;
 }
 *pslow='\0';
 return 0;
}

当它运行到“* pslow = * pfast;”...

的赋值语句时出现段错误

有人告诉我原因,提前谢谢!

1 个答案:

答案 0 :(得分:8)

您正在尝试更改导致未定义行为的字符串文字。

更改

char *str="abcdce";

char str[] ="abcdce";