Pointer - my nemesis | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pointer - my nemesis

Pointers are my wall that I couldn't brake for long time. I know it's concept but i can't find answer for one important question. Why I should use pointers to manipulate varibles that points on, when I could use that variable without using pointer. If int x = 1; int *p = &x; Then cout << x will give me 1 as well as cout << *p will give me 1. Why I should use *p when I can use x for same effect?

3rd Jan 2019, 8:04 AM
Patryk Pasu
7 Answers
+ 5
Example you gave is common in tutorials just to show how do they work. In "real world" programming their advantage is that you can manage how long the variable lives. Whenever you think you're done with it you just use "delete" operator and that's it, variable is gone. One more good thing about them is they have always fixed size, meaning it can be faster to pass pointer to the function than object itself.
3rd Jan 2019, 8:15 AM
Jakub Stasiak
Jakub Stasiak - avatar
+ 1
So, are pointers only used to optimize code efficency and decrease memory usage?
3rd Jan 2019, 8:22 AM
Patryk Pasu
+ 1
Generally speaking, yes.
3rd Jan 2019, 8:31 AM
Jakub Stasiak
Jakub Stasiak - avatar
+ 1
Thank You for explanation!
3rd Jan 2019, 8:46 AM
Patryk Pasu
0
I use pointers in my every programm that is a bit more complex than a tutorial example. Lets say you have a bunch of objects of a certain type, and in your programm there is a need to manipulate these objects in specific way. What would i do - i would create a function that takes a pointer to an already existing object and manipulates it through the pointer the way i need. This way i can call this function with the object's address as a parameter whenever i need to. Yes, you could manipulate that object without a separate function for that, but good luck with keeping your code structure in your head. You might aswell write a 1000 lines of code in one main function if you follow that mindset
3rd Jan 2019, 12:09 PM
Data
Data - avatar
0
when you get the grasp on both pointers and objects of custom types (classes), you will realise how many things you can do which you couldnt achieve before
3rd Jan 2019, 12:12 PM
Data
Data - avatar
0
one common and simple example for using pointer are the dynamic arrays, where you allocate a certain about of objects and store a pointer to the beginning of that array (and unlike with normal arrays, this amount can wary at runtime). After that you can access elements from that array as you would with a normal array. Just dont forget to deallocate the memory later Or you can start learning smart pointers for automagic deallocation
3rd Jan 2019, 12:20 PM
Data
Data - avatar