Hi there,
What helped me was to think of pointers as any other variable, but instead of numbers or text they contain addresses of memory. You could print a pointer like this:
1 2 3 4
|
int a;
int* p = &a;
std::cout << p;
|
It will print out the current address of the first byte of 'a'. In other words, the pointer
refers to the space in memory where 'a' is. Now, that's not usually what we need, we usually want to access the
value in that memoryspace. Accessing that value means we have to
dereference that address.
The dereference operator for scalar types is *:
1 2 3
|
int a = 3;
int* p = &a;
std::cout << *p; //prints 3
|
For classes and structs however, we use the arrow operator:
1 2 3 4 5 6 7
|
struct my_struct
{
int member;
} instance;
my_struct* p = &instance;
std::cout << p->member;
|
When you have an array, the brackets actually serve as a dereferencing operator:
1 2 3
|
int arr[10];
//arr[5] == arr + 5
|
The name of the array is actually a pointer to the start of the array, the brackets count 5 spaces further and dereference it for you. This happens under the hood, so you don't really realize it happens.
Now we can discuss pointers to pointers:
1 2 3 4 5 6 7 8 9 10 11
|
int a=3;
int* p = &a;
int** ptp = &p;
std::cout << p; //shows address of a
std::cout << ptp; // shows address of p
std::cout << *p; //shows 3
std::cout << *ptp; //shows address of a (content of p)
std::cout << *(*ptp); //shows 3
|
Now to your example, you said you wanted an array of pointers to objects:
1 2 3 4 5 6 7
|
//remember, arr is a pointer in its own way
Person** arr = new person* [size];
Person* p = new Person();
arr[0] = p;
std::cout << arr[0]; //prints address of first person
std::cout << arr[0]->name; //prints the name member of the first person
|
The []-operator has precedence over the -> operator (because it is to the left of it), so what happens is this:
arr[0]->name => p->name
Hope that helps.
All the best,
NwN