2
#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, thanks in advance!

1
  • 2
    Did you mean™ pslow=pfast;? Commented Mar 26, 2011 at 13:07

1 Answer 1

8

You are trying to change a string literal which leads to undefined behavior.

Change

char *str="abcdce";

to

char str[] ="abcdce";
Sign up to request clarification or add additional context in comments.

1 Comment

@witmusk: You are welcome. Since you are new and have not accepted answers to any of the questions you've asked so far, I would like to tell you that you can mark the answer that helped you to solve the problem by clicking the right mark next to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.