I don't think you understand them at all...
I wouldn't say that I'm 100% proficient, but this is how I understand them:
As parameters in a function header
Example:
1 2 3 4 5 6 7
|
void foo(int *a, int& b); //the spaces don't matter
int main()
{
int x, y;
foo(&x, y);
}
|
Inside
foo,
a is a pointer to the variable
x in
main, and
b is a reference to the actual
y inside
main. This means that modifying
b also modifies
y. To modify
x, you need to dereference
a first. (EG
*a = 10;
changes
x in
main to be 10.)
Outside of function headers
Example:
1 2 3 4
|
int x;
int *y;
y = &x;
cout << *y;
|
The second line is declaring
y as a pointer to an int. The third line assigns the address of
x to
y (used outside of function headers, the ampersand means the address of the variable it precedes). Yes, pointer variables hold memory addresses, not whatever type it is a pointer of. Line 4 is dereferencing a pointer (used outside of declarations, the asterisk is a dereference operator) and outputting the value contained in the address that
y points at.
EDIT:
And here's an example that I didn't understand until recently:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
void foo(int *a)
{
int b = 10;
a = &b;
cout << *a << endl;
}
void bar(int &*a)
{
int b = 5;
a = &b;
cout << *a << endl;
}
int main()
{
int c = 1;
int *d = &c
cout << *d << endl;
foo(d);
cout << *d << endl;
bar(d);
cout << *d << endl;
return 0;
}
|
1
10
1
5
5 |
In
main,
d contains the address of variable
c, which contains the value 1. So when you dereference
d and output it, you get 1. Then
d is passed as a parameter to the function
foo.
In foo,
a is a
copy of
d. Changing
a to point to
b in the function means that dereferencing
a gives us the value of
b (which is 10). This
does not change
d inside main. Dereferencing
d still gives us 1.
In bar,
a is a
reference to the pointer
d. Changing
a to point to
b means that
d is also changed to point to
b. Dereferencing
a or
d both gives us 5.