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';
This is a discussion on Why isnt it possible to assign individual char in char array? within the C Programming forums, part of the General Programming Boards category; char *name = "abcd"; name[2] = 'A'; (gdb) runStarting program: /home/a/src/c/ex9 Program received signal SIGSEGV, Segmentation fault. 0x000000000040052a in main ...
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";
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
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";