[ACCEPTED]-What does a const pointer-to-pointer mean in C and in C++?-constants
Your colleague is wrong. That is a (non-const) pointer 2 to a (non-const) pointer to a const MyStructure. In 1 both C and C++.
In such cases the tool cdecl (or c++decl) can 1 be helpfull:
[flolo@titan ~]$ cdecl explain "const struct s** ppMyStruct"
declare ppMyStruct as pointer to pointer to const struct s
You were right in your interpretation. Here's 5 another way to look at it:
const MyStructure * *ppMyStruct; // ptr --> ptr --> const MyStructure
MyStructure *const *ppMyStruct; // ptr --> const ptr --> MyStructure
MyStructure * *const ppMyStruct; // const ptr --> ptr --> MyStructure
These are all 4 the alternatives of a pointer-to-pointer 3 with one const qualifier. The right-to-left 2 rule can be used to decipher the declarations 1 (at least in C++; I'm no C expert).
Your colleague is wrong, and it's the same 3 for C and C++. Try the following:
typedef struct foo_t {
int i;
} foo_t;
int main()
{
foo_t f = {123};
const foo_t *p = &f;
const foo_t **pp = &p;
printf("f.i = %d\n", (*pp)->i);
(*pp)->i = 888; // error
p->i = 999; // error
}
Visual 2 C++ 2008 gives the following errors for 1 the last two lines:
error C2166: l-value specifies const object
error C2166: l-value specifies const object
GCC 4 says:
error: assignment of read-only location '**pp'
error: assignment of read-only location '*p'
G++ 4 says:
error: assignment of data-member 'foo_t::i' in read-only structure
error: assignment of data-member 'foo_t::i' in read-only structure
You are right.
Another answer already pointed to the "Clockwise Spiral Rule". I 1 liked that one very much - a little elaborate, though.
As a corollary to the other comments, don't 4 put 'const' first. It really belongs after 3 the type. That would have clarified the 2 meaning immediately, just read it RTL as 1 usual:
MyStructure const** ppMyStruct;
void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the pointee
ptr = 0; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the pointee
ptrToConst = 0; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the pointee
constPtr = 0; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the pointee
constPtrToConst = 0; // Error! Cannot modify the pointer
}
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.