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

  1. #1
    Registered User
    Join Date
    Oct 2012

    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
    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
    The problem is that you are trying to modify a string literal, which results in undefined behaviour. If you had written:
    char name[] = "abcd";
    then it would work.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

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

    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, 01: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, 03: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