put 0 in char pointer

This is a discussion on put 0 in char pointer within the C Programming forums, part of the General Programming Boards category; Why can't we put a 0 character in a char pointer? It crashes on both lines. Code: int main() { ...

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

    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;
    }
    Compiler MSVC++ 2013 with Code::Blocks.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,671
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    796
    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!
    Compiler MSVC++ 2013 with Code::Blocks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 12-02-2012, 04: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-13-2009, 11:03 PM
  5. Char-array vs Char-pointer
    By ripper079 in forum C++ Programming
    Replies: 12
    Last Post: 09-09-2002, 01:16 AM

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