Speaking of damage control:
1) When is the best time to use them?
When you need to and have no other option or when it is preferable. |
The same could be said for using airplanes, butter knives or formal attire.
Why use pointers?
When you need to. |
Ditto. If you aren't going to be helpful, please be silent.
Okay back to the original question. Why use pointers?
Technically, you can point to any memory location, but the most common use of pointers is for dynamic memory allocation. You probably already know how to create variables at compile time:
1 2
|
int a = 0;
double numbers[10];
|
But sometimes you don't how many variables you will need at compile time. So you want to tell the program to allocate room for your data while the program is running. For example, suppose you have a text file of numbers. The first line tells you how many numbers there are, and the rest of the file contains the numbers themselves. You might read them into an array allocated at runtime:
1 2 3 4 5 6
|
unsigned int num;
cin >> num;
double *arr = new double[num];
for (int i=0; i<num; ++i) {
cin >> arr[i];
}
|
The standard library has a template called vector<> that handles this sort of automatically expanding array for you.
Another trick is to create a class or struct that contains a pointer. This lets you chain dynamic memory together:
1 2 3 4 5 6 7
|
class Link {
public:
Link(int n) : val(n), next(NULL) {}
int n;
private:
Link *next;
};
|
Now you can declare one variable to point to a single link:
Link *head = NULL;
and string integers together in a chain called a linked list:
1 2 3 4 5 6
|
void add(int n)
{
Link *tmp = new Link(n);
tmp->next = head;
head = tmp;
}
|
add() creates a new Link and adds it to the front of a chain of links. head always points to the front.
There are more complicated structures that work off this basic idea: you allocate data that contains pointers to other data.
That's a top-level view. The underbelly of dynamic memory allocation is that you have to tell the program when you're done with it so it can be returned to the "free pool" and potentially allocated again. If you forget to do this you can end up with a "memory leak" or you might just run out of memory.
Well that's the elevator speech. I hope this helps.