[cs13001] Pointers question
Mikhail Nesterenko
mikhail at cs.kent.edu
Tue Nov 13 14:23:27 EST 2012
> Professor, what would happen if you have three pointers and a
> variable. The first pointer points to the variable, and second
> pointer points to the first variable, and the third pointer is a
> constant pointer that points to the second pointer. What would
> happen? So if I am thinking this correctly, it would be like
>
>
> Int * const p3 = p2 = p1 = Int i
>
> So if the const points to a pointer pointing to a pointer pointing
> to an i variable, would the const point only to the p2 memory
> location, or would it point to the variable?
>
A good way to figure out complicated C++ declarations is to read them
from right to left. For example:
const int* i; // pointer to an int that is const
int* const j; // constant pointer to a (non-const) int
int const* k; // pointer to a const int, less popular but correct form
If you want to declare a constant pointer that points to a pointer
that points to another pointer that points to an int; and then
initialize the declared pointer, it might look like this:
int i, *p, **pp;
int ***const cppp = &pp; // initializes a constant pointer to a
// pointer to a pointer to int
p = &i; // assigns p the address of i
pp = &p; // assigns pp the address of p
***cppp = 42; // assigns a new value to i
Naturally, extended chains of pointers-to-pointers (called "levels of
indirection") make the program difficult to underhand and should be
avoided or used with extreme care.
Thanks,
--
Mikhail
More information about the cs13001
mailing list