Pointers simply store memory addresses. So to point a pointer to a variable you have to pass it an address; specifically that of the variable you want the pointer to point to (read this sentence five times fast and slur your p's). To have a variable give its address in memory you must use the ampersand (&
) operator. Yes, we use this same symbol for creating reference variables, but you can read the differences by clicking here.
For example let's say we create an integer variable called x
:
int x;
And we give x
a value of 928
:
x = 928;
Well now if we put just x
somewhere it would be like writing the value 928
since that's what x
's value is. But we can't give a pointer 928
because it would interpret that as the memory address you want it to point to (which is most likely NOT where x
is located in memory). So we put the ampersand in front of x
(&x
) and pass that to the pointer variable:
int *ptr; // declare pointer variable of type integer
int x; // declare 'x' as an integer
x = 928; // put value of '928' into 'x'
ptr = &x; // give 'ptr' the memory address of 'x'
If you want to see the difference between putting the ampersand in front and not you can try the following code:
/* -example-source-1------------------------------------------------- */
#include <iostream.h>
void main()
{
int x; // create an integer variable called 'x'
x = 10; // put value of '10' into variable 'x'
cout << "the value of 'x' is " << x << endl
<< "the memory address of 'x' is " << &x << endl;
}
/* ------------------------------------------------------------------ */
When passing the address of the variable, you don't want to put the asterisk in front of the pointer:
WRONG: *ptr = &x;
RIGHT: ptr = &x;
Okay, this sounds kinda skippy but by this point you should be able to do the following things no sweat (if not go to the bottom of the page to find out how to contact me):
- declare a pointer variable (
[type] *[name];
)
- pass the address of a variable to a pointer (
)