Why pointers? (The answer)
I am actually speaking from the point of view from someone who used to think pointers were useless. They are most definately not. If you don't understand them, you have to learn, because you cannot get past the title of "Newbie" until you do.
For those of you who do not understand how pointers work, i'll try to explain.
Code:
#include <iostream.h>
int main(void)
{
int *ptr; //this creates a pointer to an integer (int). The * means it's a pointer. the actual data type is: int *
int x = 0;
ptr = &x; //sets the pointer to the address of x.
cout<<"stored in ptr is: "<<ptr<<endl;
cout<<"stored in x is: "<<x<<endl;
cout<<"stored in *ptr is: "<<*ptr<<endl; //by using * you dereference the pointer.
*ptr = 5;
cout<<"*ptr set to: "<<*ptr<<endl;
cout<<"x is now: "<<x<<endl;
return 0;
}
I hope that clears up somethings. Feel free to ask questions or add to what I've said. I am not a C++ guru, but I figured other people may have the same question I did: Why do we need to learn pointers?
I know I didn't cover everything, but I hope this will inspire some people to help the newbs learn more about pointers.
Example of the three steps
Consider the program that prompts the user to input some number and calculate something with those numbers:
Programmer at step 1:
Code:
cout << "How many numbers do you want:";
int n;
cin >> n;
int numbers[1000];
for (int i=0; i<n; ++i)
cin >> numbers[i];
calculate(numbers,n);
Programmer at step 2:
Code:
cout << "How many numbers do you want:";
int n;
cin >> n;
int* numbers = new int[n];
for (int i=0; i<n; ++i)
cin >> numbers[i];
calculate(numbers,n);
delete[] n;
Programmer at step 3:
Code:
cout << "How many numbers do you want:";
int n;
cin >> n;
vector<int> numbers(n);
for (int i=0; i<n; ++i)
cin >> numbers[i];
calculate(numbers,n);
Perhaps you think that the last two are equally good, but they are not! There is a potential memory leak if you forget to delete[] the memory you allocated.
If you think it is extremly easy to remember such a thing, remember that error handling in C++ is done via exceptions, what happens if calculate() throws an exception? The level 3 example handles this, the level 2 does not.
Pointers win by my standards.
After all this, I still like pointers more than references. pointers can pretty much do all that references can and more.
sure you have to use * and & more...who cares?!