Pointers contain a memory address. You can access stuff in that address through the pointer. You can change the memory address the pointer is pointing to by assigning it a new value, for example from another pointer. A null pointer just contains the value NULL (typically used in C), or 0 (typically used in C++), or nullptr (used in the upcoming C++ standard C++0x), and signifies that the pointer actually does not point anywhere.
Dynamic memory allocation returns a pointer to the newly allocated memory. In C++ dynamic memory allocation is done with the operators
new and
delete.
New takes a type and for classes optionally a constructror parameter list.
For example to allocate a few things:
Code:
int* ip = new int;
string* sp = new string;
string* sp2 = new string("Hello World!");
Now, the memory of those int and string variables is not freed until you say so using
delete. Delete takes a pointer to dynamically allocated memory and frees it.
If you lose the last pointer to your dynamically allocated memory, you can no longer free it and your program will leak memory!
Now to free the memory allocated above:
Code:
delete ip;
ip = 0;
delete sp;
sp = 0;
delete sp2;
sp2 = 0;
Notice that I nulled the pointers because they no longer point to an allocated portion of memory. You can also allocate and delete arrays of things, but that's less commonly needed.
Function pointers just point to the memory address where the function code resides. It can be used to call the function without knowing its proper name. Nice if you for example want to give a function as a function parameter or do something resembling functional programming in C++).
Void pointers are "pointers to anything". It usually means the type of data behind the pointer depends on runtime information. In that case the void pointer needs to be
cast (means changing the type a variable is treated as) to another type, but you need to figure out from the code what it should be cast into. Don't use these lightly, as they break type checking and make your code really hard to follow if used improperly.
Pointers are just integers that signify memory addresses. Because the language is aware of this, pointers can have strong typing (type checking) and other nice stuff.