I don't understand Double Pointers?

So I understand pointers for example

1
2
3
int a = 10;
int* b;
b = &a;


Now b holds the memory address of b and if you wanted the value
you could dereference again with
 
*b


That's all fine and dandy and a pointer to a pointer is really confusing? How would I get the value of a using that and can someone explain?

I've tried things like
1
2
3
int a = 10;
int **b;
b = &a;


I don't really have any idea how to use it though. Can someone explain? Thanks guys
I believe something like this:

std::cout << *(*b) << std::endl;

The only time I use pointer to pointer is either when passing a pointer to a function then I can accept the parameter as pointer to pointer. Another case is when declaring an array of pointers, then the array is a pointer to pointer type.

Or in your case, although the use of pointers here is almost never going to see light of day in the real world because it is just unnecessary:
1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main () {

	int a = 10;
	int *b = &a;
	int **c = &b;
	std::cout << *(*c) << std::endl;
	return 0;
}
Last edited on
First of all, there's no such thing as double pointer. Put the idea out of your head if you ever want to understand pointers.

It's possible that the part you're missing is that a pointer is a variable.

So let's look at your example:
1
2
3
int a = 10;
int* b = &a;
int** c = &b;


a is a variable. Its content is the value 10.

b is a variable. Its content is the address of variable a.

c is a variable. Its content is the address of variable b.

Ok, here's a full program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
        int a = 10;
        int* b = &a;
        int** c = &b;

        std::cout << "a = " << a << std::endl;
        std::cout << "b = " << b << std::endl;
        std::cout << "c = " << c << std::endl;
        std::cout << "address of c = " << &c << std::endl;

        return 0;
}


And this is the output
a = 10
b = 0x22ac8c
c = 0x22ac88
address of c = 0x22ac84


What does it all mean?

We have three variables a, b, c that are 4 bytes long and sit next to each other at addresses 0x22ac8c, 0x22ac88, 0x22ac84 respectively.

a has value 10 and is at address 0x22ac8c.

b has value 0x22ac8c and is at address 0x22ac88.

c has value 0x22ac88 and is at address 0x22ac84.

We treat the 10 at 0x22ac8c as an int, the 0x22ac8c at 0x22ac88 as the address of an int, and 0x22ac88 at 0x22ac84 as the address of the address of an int.

This interpretation is what the type of a variable is. And the syntax for expressing an int int, the syntax for expressing the address of that is int*, and the syntax for expressing the address of that is int**.
Last edited on
Topic archived. No new replies allowed.