Const char pointer assignment

Are the following appointments available? Or any of them will 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 this normal?

 const char * c5 = "xyz"; char * c6 = "abc"; c2 = c5; c2 = c6; 
+7
source share
4 answers

In your mind, draw a line through the asteric. On the left is what the right indicates, and what type of pointer

for example

  • const char * const p - the pointer p is constant, and therefore the characters pointed to by p , that is, cannot change both the pointer and the contents, to which p points to
  • const char * p - p points to constant characters. You can change the value of p and make it point to different constant characters. But no matter what p points to, you cannot change the contents.
  • char * const p - You cannot change the pointer, but you can change the contents

and finally

  • char * p - everything to capture

Hope this helps.

+30
source

All are valid statements, since you do not play them out because all pointers remain uninitialized or do not point to any valid memory locations.

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

+9
source

These appointments all work perfectly, as I and others explained in your recent launch of almost the same questions.

A const char* is a pointer to memory that cannot be changed using this pointer. Nothing can get around this. The compiler will mind if you set c4 = c1 since then to bypass const.

+3
source

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

0
source

All Articles