C++ pointer to const pointer

  • A+
Category:Languages

I'm still confusing where to place const in pointers with more than one indirection. Can someone clarify?

E.g. right now I need a pointer to const pointer, meaning such a variable int **ppTargets that I can assign int *pTargets variable to it, like:

int foo(int **ppTargets) {     int *pTargets = /* calculate here */;     *ppTargets = pTargets;     return 37; // just e.g. } 

The above code lacks const. So in foo I want pTargets to point to constant memory and be unassignable after initialization (so that one cannot write e.g. pTargets++), that would be int const *const pTargets = /* assigned once */. Next I want to declare ppTargets that ppTargets itself can be assigned, but then *ppTargets can only be read.

In the other words, in the caller code I want:

int const* pTargets; foo(&pTargets); 

I tried to declare foo as follows, but get an error you cannot assign to a variable that is const:

int foo(int *const *const ppTargets) 

 


What you're looking for is int const * const * ppTarget. No, wait, you're looking for int const ** const ppTarget. No no, it's int * const * const * ppTarget.

Chances are one of them is correct (I'm betting the first one). However, you don't want people reading your code to guess what it is you mean. It's just too confusing. C++ can do that to you.

What you should do, is use typedefs to make sure people who read the code understand what you want.

typedef const int *CINT_PTR; CINT_PTR pTarget = ....; CINT_PTR *ppTarget = &pTarget; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: