Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Pointer to constant pointer to integer constant (const int * const * variable)

Given an example

const int limit = 500;
const int * const cpci = &limit;
const int * const * pcpci = &cpci;

I am having difficulty understanding what the last line means.

Basically in array terms the value pcpci it's just an array of (const int * const)'s. But i can't seem to make multiple copies inside pcpci since it is not supposed to be a constant pointer.

For Example

const int limit = 500;
const int * const cpci = &limit;
const int * const * pcpci = &cpci;
const int limit2 = 600;
const int * const cpci2 = &limit2;
*(pcpci+1) = &cpci2;

In the last line of the above code i got "error lvalue must be modifiable". But i was wondering why is this happening since pcpci is not a constant pointer and only it's elements should be constant and non modifiable.

like image 743
Node.java Avatar asked May 06 '26 07:05

Node.java


2 Answers

First of all this statement

*(pcpci+1) = &cpci;

has undefined behaviour because you may not dereference a pointer that does not points to an object. You could use this construction if pcpci would point to an element of an array and pcpci + 1 also point to the next element of the same array.

So it would be more coorectly to write

*(pcpci) = &cpci;

However the object pointed to by pcpci is a constant object with type T const where T is const int * so it may not be reassigned.

That it would be more clear you can rewrite definition

const int * const * pcpci = &cpci;

the following way

typedef const int * const ConstPointerToConstObject;

ConstPointerToConstObject * pcpci = &cpci;

So if to derefernce pcpci you will get an object of type ConstPointerToConstObject that may not be changed because it is a constant pointer to constant object.

like image 79
Vlad from Moscow Avatar answered May 08 '26 20:05

Vlad from Moscow


But i was wondering why is this happening since pcpci is not a constant pointer

No, but *(pcpci+1) is. It has type const int* const. Obviously you can't assign anything to that.

like image 40
Lightness Races in Orbit Avatar answered May 08 '26 19:05

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!