I'm trying to make a non-constant array of non-constant pointers to constant objects. The idea is that I should be able to change what the pointers in the array point to, but what they point to is a constant object.
I'm having problem defining this array (it's an array of pointers to objects of type Person
- a custom class). I'm currently declaring the array like so:
Person* people[10];
Also that's not explicitly saying that the pointers point to const Persons. So when I do something like this:
people[i] = &p;
where p
is a reference to an object of type const Person
, it fails.
A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.
An array of pointers is an array that consists of variables of pointer type, which means that the variable is a pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer pointers; then its declaration would look like: int *ptr[5]; // array of 5 integer pointer.
We declare a pointer to constant. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of 'ptr'.
The name of the array A is a constant pointer to the first element of the array. So A can be considered a const int*. Since A is a constant pointer, A = NULL would be an illegal statement. Arrays and pointers are synonymous in terms of how they use to access memory.
When in doubt ... use typedef (because it's explicit, adds more specialized semantics and avoids the confusion completely):
typedef const Person* PersonCPtr;
PersonCPtr people[10];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With