Why isnt it possible to assign individual char in char array?

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 ...

  1. #1
    Registered User
    Join Date
    Oct 2012
    Location
    Sweden
    Posts
    1

    Question Why isnt it possible to assign individual char in char array?

    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';

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    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.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,306
    The problem is that you are trying to modify a string literal, which results in undefined behaviour. If you had written:
    Code:
    char name[] = "abcd";
    then it would work.
    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

  4. #4
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    It is possible, but that is a string literal and modifying it is undefined behavior. Try this instead:

    Code:
    char name[] = "abcd";
    BTW, if you are using a string literal, add a const qualifier, it will prevent you from modifying it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Manipulating private individual char elements
    By Know_Your_Role in forum C++ Programming
    Replies: 4
    Last Post: 03-31-2009, 02:18 PM
  2. Replies: 3
    Last Post: 11-17-2008, 12:36 PM
  3. How to assign ';' to a char?
    By meili100 in forum C++ Programming
    Replies: 4
    Last Post: 05-22-2008, 04:08 AM
  4. Assign value of multiple char array elements to int
    By 3saul in forum C Programming
    Replies: 3
    Last Post: 02-03-2006, 05:31 AM
  5. why can't you assign a char to a char?
    By yahn in forum C++ Programming
    Replies: 9
    Last Post: 12-04-2005, 11:31 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21