const char pointer assignments

前端 未结 4 2120
借酒劲吻你
借酒劲吻你 2020-12-10 17:02

Are the following assignments valid? Or will any of these create problems. Please suggest.

const char * c1;  
const char * c2; 
const char * c3;
char * c4;

         


        
相关标签:
4条回答
  • 2020-12-10 17:49

    All of these are valid, the only problematic line is char * c6 = "abc";: here "abc" is a const literal so assigning it to a non-const pointer is not safe, and should at least generate a warning if not a compile error (I did not try to compile it).

    0 讨论(0)
  • 2020-12-10 17:51

    In your mind draw a line through the asterik. To the left is what is being pointed to and to the right what type of pointer

    For example

    1. const char * const p - The pointer p is constant and so are the characters that p points to - i.e. cannot change both the pointer and the contents to what p points to
    2. const char * p - p points to constant characters. You can change the value of p and get it to point to different constant characters. But whatever p points to, you cannot change the contents.
    3. char * const p - You are unable to change the pointer but can change the contents

    and finally

    1. char * p - Everything is up for grabs

    Hope that helps.

    0 讨论(0)
  • 2020-12-10 17:51

    All are valid statements as along you don't dereference them because all the pointers are left uninitalized or aren't pointing to any valid memory locations.

    And they are valid because pointer is not constant but the value pointed by the pointer is constant. So, pointers here are reassignable to point to a different location.

    0 讨论(0)
  • 2020-12-10 17:52

    These assignments are all perfectly valid as I and others have explained in your recent run of near identical questions.

    A const char* is a pointer to memory that cannot be modified using that pointer. Nothing here can circumvent that. The compiler would object if you assigned c4 = c1 since then that would circumvent the const.

    0 讨论(0)
提交回复
热议问题