How to fix this?Code:#include <stdio.h> int main() { char* string="monkey"; char* ptr=string; *ptr='d'; puts(string); // Seg fault error }
This is a discussion on Change one letter from a string within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> int main() { char* string="monkey"; char* ptr=string; *ptr='d'; puts(string); // Seg fault error } How to fix ...
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.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
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";