How to fix this?Code:#include <stdio.h>
int main() {
char* string="monkey";
char* ptr=string;
*ptr='d';
puts(string); // Seg fault error
}
Printable View
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.
Redefine stringCode:char string[]="monkey";
Are you trying to make a donkey out of me? :p
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";