Thread: put 0 in char pointer

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    put 0 in char pointer

    Why can't we put a 0 character in a char pointer?
    It crashes on both lines.
    Code:
    int main()
    {
        char * buf = "hello world";
      
        buf[5] = '\0';
        buf+5  = '\0';
    
        return 0;
    }
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    It's because buf is pointing to a string constant, and the OS steps in and kills the program when it attempts to modify read-only memory.

    Put it in a char array for success.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Ah yeah, of course I knew that and forgot about it.
    I just thought when you pass a char array in a function you could modify it but its the same.

    Thanks Salem!
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-02-2012, 05:25 AM
  2. Read char by char into two-dimensional array pointer.
    By 'Serj Codito in forum C++ Programming
    Replies: 5
    Last Post: 09-08-2012, 09:47 AM
  3. Copy char array to char pointer
    By Suseela in forum C Programming
    Replies: 9
    Last Post: 08-06-2009, 12:49 PM
  4. pointer to pointer that points to a char array
    By steve1_rm in forum C Programming
    Replies: 2
    Last Post: 01-14-2009, 12:03 AM
  5. Char-array vs Char-pointer
    By ripper079 in forum C++ Programming
    Replies: 12
    Last Post: 09-09-2002, 01:16 AM