How to fix this?Code:#include <stdio.h> int main() { char* string="monkey"; char* ptr=string; *ptr='d'; puts(string); // Seg fault error }
How to fix this?Code:#include <stdio.h> int main() { char* string="monkey"; char* ptr=string; *ptr='d'; puts(string); // Seg fault error }
By not doing this:
Code:*ptr='d';
Basically, you are not allowed to change a string literal. Any attempt to do so results in undefined behaviour.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Redefine stringCode:char string[]="monkey";
Are you trying to make a donkey out of me?
Code:#include <stdio.h> #include <string.h> int main() { char string[]={"monkey"}; char* ptr=NULL; ptr= strchr(string, 'm'); if(ptr) *ptr='d'; puts(string); return 0; }
when you intialize a string constant to char pointer, the stringconstant is stored in a text or code (Which is read-only file).
So, redefine to a char arrayCode:char *string="monkey";
Understand the difference between string and string constant.Code:char string[]="monkey";