Quick pointer question

1
2
3
4
5
6
7
8
9
    int x = 25;
    int* ptr1;
    int* ptr2;

    ptr1 = &x;
    ptr2 = &ptr1;  // doesn't work.

    cout << ptr1 << endl;
    cout << ptr2 << endl;


I am just starting learning pointers. I was wondering why I couldn't do ptr2 = &ptr1. Doesn't a pointer have its own memory address where it stores the memory address of x? I am trying to understand how it works.
You must understand how you declare pointers.
Take a close look at lines 3 and 6.
int* ptr2;
"ptr2 points to an integer type"
ptr2 = &ptr1;
"the address of ptr1 is assigned to ptr2".

The compiler is complaining because ptr2 is supposed to point only to integers, not to another pointer (to an integer or whatever else).

You can fix this by declaring ptr2 a pointer to (a pointer to an integer) with int **ptr2;
"ptr2 is a pointer to (a pointer to an integer).
You almost always read pointers right to left.
As an alternative, you can declare ptr2 a void pointer. Void pointers can point to any type. However void pointers cannot be dereferenced because it can be pointing to any type and hence cannot know what size of whatever it is pointing to.
Last edited on
Thanks.
Topic archived. No new replies allowed.