const char pointer assignments
Solution 1
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
-
const char * const p
- The pointerp
is constant and so are the characters thatp
points to - i.e. cannot change both the pointer and the contents to whatp
points to -
const char * p
-p
points to constant characters. You can change the value ofp
and get it to point to different constant characters. But whateverp
points to, you cannot change the contents. -
char * const p
- You are unable to change the pointer but can change the contents
and finally
-
char * p
- Everything is up for grabs
Hope that helps.
Solution 2
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.
Solution 3
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.
Related videos on Youtube
user32262
Updated on June 04, 2022Comments
-
user32262 almost 2 years
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; c2 = c1; c2 = c3; c2 = c4;
What if I do the following, is that ok thing to do?
const char * c5 = "xyz"; char * c6 = "abc"; c2 = c5; c2 = c6;
-
user32262 over 12 yearsI apologise if I am asking same thing. Maybe my understanding with pointers is not acurate.
-