As Moschops already said, a pointer IS a normal variable that store addresses which "points" to some bytes somewhere in memory.
For example an
int *
stores an address that points to some position in memory where you say there should be an int. It might be an integer there, but you could also do this:
1 2 3
|
float f = 4;
int * p = (int*) &f;
cout << *p << endl;
|
This code allows you to interpret the bytes that represent the float value 4 as an integer. This wont print out 4, as int and float store the value in different ways, it'll just print out some random number.
The code above is just an example, it's nothing you should write.
The main reason to use a pointer is to send the address to some large quantity of data rather than copying the data around. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
struct DATA {
char v[1024]; // A 1 kB array with characters
};
void f1(DATA d) {
// DONT DO THIS!
// This would COPY the ENTIRE 1 kB array with characters, and would be extremely inefficient
// if all you want to do in this function is to read the data. Also if you alter d, you'd alter a
// temporary copy of a DATA struct.
}
void f2(DATA * p) {
// Here you receive an address to some existing DATA struct; however you might want to
// verify that this is a real address, and not for example NULL (0), which is used as a
// value that tells us this DATA pointer doesnt point at anything.
// If you would use this address and alter the structure, you would alter the a
// NON-temporary DATA struct.
}
int main()
{
DATA d = {"Some content"};
f1(d); // Send a copy of d to f1; f1 CANNOT change d
f2(&d); // Send the address of d to f2; f2 CAN change d
}
|
There's also references in C++, which works like pointers, but you can skip some syntax using a reference rather than a pointer.
Hope this helps. There are more differences, but I'll save that for someone else :)).
// Sorglig