Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ const double pointer

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.

like image 254
chaviaras michalis Avatar asked Dec 17 '17 10:12

chaviaras michalis


People also ask

Can you have a double pointer in C?

Master C and Embedded C Programming- Learn as you go A pointer is used to store the address of variables. So, when we define a pointer to pointer, the first pointer is used to store the address of the second pointer. Thus it is known as double pointers.

What is const double?

Declaring a variable to be const means that its value cannot change; therefore it must be given a value in its declaration: const double TEMP = 98.6; // TEMP is a const double. ( Equivalent: double const TEMP = 98.6; )

What is const pointer in C?

A constant pointer is one that cannot change the address it contains. In other words, we can say that once a constant pointer points to a variable, it cannot point to any other variable. Note: However, these pointers can change the value of the variable they point to but cannot change the address they are holding.

Can pointer be double?

So, when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.


1 Answers

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
like image 73
melpomene Avatar answered Sep 20 '22 01:09

melpomene