Node.java
Node.java

Reputation: 33

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.

Upvotes: 3

Views: 211

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

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.

Upvotes: 2

Related Questions