Here's a visual which might help. Keep it open as you read my explanation:
http://imgur.com/3Rf50RG
Variables are essentially a "box" that contains information. You can think of memory as millions and millions of these boxes available to you.
Each box has an "address" that tells the computer where to find it in the sea of other boxes. So whenever you make a variable, that variable is assigned an address in memory:
1 2
|
int foo = 5;
int bar = 10;
| |
For this example, let's say that the computer decides to place 'foo' at address '1002' and 'bar' is placed at address '1006'
The value of '5' is then placed inside the box at address 1002
and the value of '10' is placed inside the box at address 1006
Pointers are variables just like regular ints. Only instead of holding a number, they hold
an address.
|
int* ptr = &foo; // let's say 'ptr' is placed at address 1004
| |
Here, the & symbol is the
address of operator. It gives us the address of foo... which, for our example, is 1002.
This means that the value of 1002 (address of foo) is placed in the box at address 1004 (address of ptr).
This is all represented in the above linked image.
So how when you work with normal variables, you can use the variable name to access the contents of that box:
1 2 3 4
|
cout << foo; // <- this will print '5' because the contents of the 'foo' box contains 5
cout << ptr; // <- this will print '1002' because the contents of the 'ptr' box contains 1002
// (assuming that's the address of foo. Note that the computer will likely put it at a
// different address so if you try this for real it will print something else)
| |
The difference with pointers is that you can use "indirection" with them. This allows you to "follow" their address:
|
cout << *ptr; // <- this will print '5'. See below
| |
Here, the * symbol is the
indirection operator. This means, instead of printing the contents of the ptr box... it will look in the pointer box, get that address, then look in whatever box that is at that address.
So
*ptr
will look in the ptr box, see that it contains 1002, then will
go to address 1002, and print the contents of
that box.
And since box 1002 contains '5', that's what it will print.
EDIT: bigtime ninja'd =P