Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char pointer assignments

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;
like image 952
user32262 Avatar asked Oct 12 '11 06:10

user32262


2 Answers

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.

like image 134
Ed Heal Avatar answered Sep 19 '22 03:09

Ed Heal


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.

like image 38
Mahesh Avatar answered Sep 21 '22 03:09

Mahesh