The Mysterious char*

This is a discussion on The Mysterious char* within the C++ Programming forums, part of the General Programming Boards category; I have always been confused about the working of char* pointer. It seems to behave quite strangely. Unlike the int ...

  1. #1
    Registered User Waleed Mujeeb's Avatar
    Join Date
    Jan 2012
    Posts
    22

    The Mysterious char*

    I have always been confused about the working of char* pointer.
    It seems to behave quite strangely.

    Unlike the int or float pointer, the char* pointer seems to be able to store an address and also a string?
    1.can some one explain this dual behavior of char*?

    Code:
    Program
    
    int main( )
    {
    char* p;
    
    //Works
    p="Hello";
    
    //Prints correctly
    cout<<p;
    
    //Does not work
    cin>>p;
    
    return 0;
    
    }
    2.why p="Hello" works? its a pointer shouldn't it give an error because "hello" is not an address, its a string?

    3. And why cin>>p doesn't work?
    Last edited by Waleed Mujeeb; 05-14-2012 at 10:39 AM.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,558
    Because "strings" are arrays, and as you know, an array reference decays into a pointer to the first element of that array.

    The compiler takes each "string", and effectively turns it into
    Code:
    static const char anonymous_string_1[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
    So when you write
    p="Hello";
    the compiler has done something like
    p = anonymous_string_1;


    > 3. And why cin>>p doesn't work?
    Because the "string" is a const, and you can't modify things which are constant.
    On most systems, a "string" is also stored in read-only memory. Attempting to write to it causes the OS to just kill the program with a segmentation fault (or similar).
    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
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,262
    1.can some one explain this dual behavior of char*?
    O_o

    There isn't any; none so different from other pointers anyway.

    An array may always decay into a pointer (to the first element of the array). That's true for every kind of type.

    The string literal syntax is just convenience to define a character array instead of doing it one character at a time.

    The type of "Hello" is `const char[6]'; it naturally decays into `const char *' exactly as it should.

    Code:
    p="Hello";
    This does not work; that's a deprecated conversion from a constant string literal to a mutable character pointer. If your compiler doesn't complain, consider supplementing your existing compiler with another one. You should make `p' a pointer t a constant value.

    Code:
    cin>>p;
    This does work. It is an illustration of a bug because, as above, `p' points to memory that isn't supposed to be changed. The expression is fine and will behave correctly if `p' pointed to a writable address. Define a character array (`char lBuffer[16];') and point `p' at that location and enter a string less than 16 characters long.

    Soma

  4. #4
    Registered User Waleed Mujeeb's Avatar
    Join Date
    Jan 2012
    Posts
    22
    hmm a little bit clear. Just asking, is the C++ string data type an alternative to char*? Any potential side effects of not using char*?

  5. #5
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    Quote Originally Posted by phantomotap View Post
    There isn't any; none so different from other pointers anyway.
    .....
    The string literal syntax is just convenience to define a character array instead of doing it one character at a time.
    Doesn't the second sentence contradict the first ?
    I mean, you can't give cout an address to a null terminated integer array and expect the array to be printed.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  6. #6
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,262
    >_<

    Ninja'd!

    Just asking, is the C++ string data type an alternative to char*?
    If you use `std::string' correctly you'll find that it is not an "alternative" to `char *'; it is a facility that is better to represent the default character set and more limitedly wide characters string resources in every conceivable way.

    Soma

  7. #7
    Registered User manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    Kolkata@India
    Posts
    2,498
    Quote Originally Posted by Waleed Mujeeb View Post
    hmm a little bit clear. Just asking, is the C++ string data type an alternative to char*? Any potential side effects of not using char*?
    I can't think of 'side-effects', but there sure are many benefits.
    Manasij Mukherjee | gcc-4.8.2 @Arch Linux
    Slow and Steady wins the race... if and only if :
    1.None of the other participants are fast and steady.
    2.The fast and unsteady suddenly falls asleep while running !



  8. #8
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,262
    Doesn't the second sentence contradict the first ?
    How so?

    The first part describes the behavior of all pointers with respect `char *'.

    The second part describes the syntactical sugar the language provides to define a "C string" which is an array.

    The array isn't a pointer; it decays into a pointer. The type `const char[6]' is not the same as the type `const char *'. However, the type `const int[6]' behaves with respect to `const int *' in the same ways.

    I mean, you can't give cout an address to a null terminated integer array and expect the array to be printed.
    Yes, you can.

    A "C string" is a convention that says "This is an array of unknown length terminated by a null character.". The "null" character is just a value. The operation you reference conceptually reads values one character at a time from the known location and prints them until the terminating character is found.

    If you choose to define an "integer series" as a sequence of values terminated by `~static_cast<uint_t>(0)' a function for this sequence that follows the same conceptual logic can be made.

    [Edit]
    For context, by using Salem's post, here is bit more information.

    Code:
    static const char anonymous_string_2[] = {'H', 'e', 'l', 'l', 'o'};
    The array `anonymous_string_2' is not a "C string"; the array `anonymous_string_2' is of type `const char[5]' and decays into the pointer `const char *' exactly as `anonymous_string_1'.
    [/Edit]

    Soma
    Last edited by phantomotap; 05-14-2012 at 11:34 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mysterious error
    By deeisenberg in forum C Programming
    Replies: 8
    Last Post: 04-30-2012, 03:51 PM
  2. mysterious seg fault!
    By MK27 in forum C++ Programming
    Replies: 12
    Last Post: 03-12-2010, 01:29 AM
  3. Mysterious Seg Fault
    By Akalic in forum C Programming
    Replies: 6
    Last Post: 10-26-2009, 04:16 PM
  4. mysterious code.......(??)
    By deltabird in forum C Programming
    Replies: 7
    Last Post: 04-11-2003, 03:58 PM
  5. Mysterious message from vVv
    By sean in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 06-08-2002, 04:11 PM

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