10

I want to make a constant double pointer points to a constant pointer points to a constant double. I started to make it (of course I make a little search at books and I googled it) from scratch and think what the following three make:

const double* cp; //pointer to a constant double
double *const cp; //constant pointer
const double *const cp; //constant pointer to a constant double

I thought the next step is to write a constant double pointer

double **const cp;// double constant pointer

then I combine the last two statements and I write

const double *const cp = arr[0];
double **const cp1 = arr ;

where arr is a dynamically allocated double dimension array. After that I tried to verify what I have done and I wrote the below statements expecting to produce error all of them.

**cp1 = 1;    // didn't produce error  
*cp1 = arr[4];    // didn't produce error
cp1 = new double*[5]; //produce error   

So the thing is that I couldn't make what I described above , a constant double pointer points to a constant pointer points to a constant double. How can I make it ?

Thanks in advance.

cpplearner
  • 13,776
  • 2
  • 47
  • 72
  • 1
    Recommended read: https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr – user0042 Dec 17 '17 at 10:52
  • A "double pointer" is not a thing in C++. What you're playing with here is a "pointer to pointer". – mlp Jul 15 '19 at 15:57

1 Answers1

25

There's only one const in

double **const cp1 = arr ;
//       ^^^^^

so I'm not sure why you're expecting the other two assignments to produce an error.

If you want it to be const on all levels, you need

const double *const *const cp1 = arr;
//                         ^ cp1 is ...
//                  ^ a const pointer to ...
//           ^ a const pointer to ...
// ^ a const double
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 2
    Thank you so much, not only for the answer but for your explanation below your code with your comments. Even in books I didn't find an explanation like this only examples . – chaviaras michalis Dec 17 '17 at 11:01
  • 5
    I would like to elevate this answer to holy status. This is a great explanation for begginers about how pointers should be read and I think it should be present in more places around communities like this. – Matias Chara Jun 21 '20 at 21:02