+ 1
I know it's a common question, but I still don't get it, when do we use pointers? + example if possible
3 Answers
+ 2
You know how you use numbers to index arrays?
int things[3] = { 15, 150, 43 };
int index = 1;
cout << things[index]; // 150
You could now, in theory, only carry around the index, and you would know to plug it back into the array when you need to.
Now imagine all the gigabytes of memory in your computer as a single big array.
int memory[];
Any variable you use lives somewhere in this array. A pointer to that variable is like the index above.
string x = "Hello!";
string* ptr = &x; // ptr is now our index
cout << *ptr; // We index the array. "Hello!"
+ 2
They have two main usecases.
The first is lists:
char* foo = "Hello world";
is a list of `char`. In C++ you try to use `std::vector` if possible.
The other is to prevent copying:
void double(int x){
x = x+x;
}
void double2(int* x){
*x = *x + *x;
}
int foo = 4;
double(foo);
// This does nothing, because `double` gets a copy of `foo`.
double2(&foo);
// This changes `foo` to 8, because wenare just passing around the index, not the value.
In C++, we mostly use references instead of pointers for that use case.