char *name = "abcd";
name[2] = 'A';
(gdb) runStarting program: /home/a/src/c/ex9
Program received signal SIGSEGV, Segmentation fault.
0x000000000040052a in main (argc=1, argv=0x7fffffffe238) at ex9.c:9
9 name[2] = 'A';
char *name = "abcd";
name[2] = 'A';
(gdb) runStarting program: /home/a/src/c/ex9
Program received signal SIGSEGV, Segmentation fault.
0x000000000040052a in main (argc=1, argv=0x7fffffffe238) at ex9.c:9
9 name[2] = 'A';
Because that's not a char array, it's a string literal. Change it to a true char array if you want to change the contents.
The problem is that you are trying to modify a string literal, which results in undefined behaviour. If you had written:
then it would work.Code:char name[] = "abcd";
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It is possible, but that is a string literal and modifying it is undefined behavior. Try this instead:
BTW, if you are using a string literal, add a const qualifier, it will prevent you from modifying it.Code:char name[] = "abcd";