+ 1

I know it's a common question, but I still don't get it, when do we use pointers? + example if possible

29th Dec 2018, 12:44 PM
mmm...
mmm... - avatar
3 Respuestas
29th Dec 2018, 1:18 PM
LetterC67
LetterC67 - avatar
+ 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!"
29th Dec 2018, 2:12 PM
Schindlabua
Schindlabua - avatar
+ 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.
29th Dec 2018, 2:16 PM
Schindlabua
Schindlabua - avatar