DEV Community

catalinarm1
catalinarm1

Posted on

pointers

Hello guys, i'm trying to undestand "pointers" and i'm struggling a bit. Could you please explain me the basics of this prototype, what can i do with a pointer, how do i integrate them into a basic problem(at first)? Thank you.

Top comments (1)

Collapse
 
veevidify profile image
V • Edited

Short answer: variable holds the value and pointer holds the memory address.

When you declare 2 variables with the same value, they live in different memory space, rough example:

int varA = 5; // &varA == 0000
int varB = 5; // &varB == 0004

When you declare 2 pointers with the same value, they refer to the same memory space:

int* ptX = &varA; // ptX == 0000; but *ptX == 5;
// *pointerName is basically getting the value at the memory space that pointerName is refering to.

similarly, another ptY also refering to the memory space that varA lives in.

int* ptY = &varA; // ptY == 0000; *ptY == 5;

When you change varA, both ptX and ptY are aware of the updated value since they refer to where varA lives:

varA = 7; // *ptX == 7; *ptY == 7

So why is this useful? How could this meta programming be utilised? 2 scenarios on top of my head:

A. Function that updates its argument:

This is not always a good idea, but in C, when you call a function, the arguments you pass to it are copied in order to execute the code inside:

void notUpdating(int myVar) {
    myVar = myVar + 1;
}
int var = 5;
notUpdating(var); // var == 5

What happens here is that var is copied, so myVar within the function is not the same as the var you declare, thus modifying myVar has no effect on var. On the other hand:

void updating(int& myVar) {
    myVar = myVar + 1;
}
int var = 5;
updating(var); // var == 6

This is called passing by reference, where you don't want the function to copy you arguments but rather refer to the same variables.

B. Dereferencing objects.

When you declare a class and create multiple objects from that class, in many cases it doesn't make much sense to "compare" 2 objects with ==.

More specifically, what are we comparing? Is it the value of each property that both objects hold? What about object that holds other objects as its property, how deep are we descending? What about object that has lambda function as its property, which get created by its caller? How do you "compare" 2 functions?

So in many cases you deal with object reference, or object pointer (referring to the memory space that your object lives in), and you ask the question "are these 2 pointing to the same object?".

And since objects usually represent something meaningful, e. g. User object represents an actual user, you want to have several methods referring to/ updating 1 User object living in memory (using a User pointer), instead of creating multiple User objects and let their values go out-of-sync with each other.