Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intuitively explaining pointers and their significance?

I'm having a hard time understanding pointers, particularly function pointers, and I was hoping someone could give me a rundown of exactly what they are and how they should be used in a program. Code blocks in C++ would be especially appreciated.

Thank you.

like image 913
Bob John Avatar asked Dec 03 '22 02:12

Bob John


2 Answers

The concept of indirection is important to understand.

Here we are passing by value (note that a local copy is created and operated on, not the original version) via increment(x):

pass by value

And here, by pointer (memory address) via increment(&x):

pass by pointer

Note that references work similarly to pointers except that the syntax is similar to value copies (obj.member) and that pointers can point to 0 ("null" pointer) whereas references must be pointing to non-zero memory addresses.

Function pointers, on the other hand, let you dynamically change the behaviour of code at runtime by conveniently passing around and dealing withh functions in the same way you would pass around variables. Functors are often preferred (especially by the STL) since their syntax is cleaner and they let you associate local state with a function instance (read up about callbacks and closures, both are useful computer science concepts). For simple function pointers/callbacks, lambdas are often used (new in C++11) due to their compact and in-place syntax.

like image 120
Preet Kukreti Avatar answered Dec 21 '22 16:12

Preet Kukreti


The pointer points to the point, is an integer value that has the address of that point. Pointers can point to other pointers. Then you can get the values more-indirect way.

Reference operator (&): You may equate a pointer to a reference of a variable or a pointer.

Dereference operator (*): You may get the value of cell pointed by the pointer.

Arrays are decayed into a pointer when passed to a function by not a reference.

Function pointers are not inlined and makes program more functional. Callback is an example to this.


enter image description here


enter image description here


enter image description here


enter image description here


enter image description here

like image 38
huseyin tugrul buyukisik Avatar answered Dec 21 '22 15:12

huseyin tugrul buyukisik