Char pointer assignment segment fault
#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;
}
segment fault when it runs to the assignment statement of "*pslow=*pfast;"...
Somebody tell me why, t开发者_如何学JAVAhanks in advance!
You are trying to change a string literal which leads to undefined behavior.
Change
char *str="abcdce";
to
char str[] ="abcdce";
精彩评论