DEV Community

Cover image for FUNDAMENTALS - POINTERS ARE EASY
feitoza
feitoza

Posted on • Updated on

FUNDAMENTALS - POINTERS ARE EASY

You could already have heard about this guy and imagined it as a Hydra from D&D. So today we gonna talk about pointers and show how easy it is.

Yes, we have to talk about Memory

But before we talk about them, let's see how our programs handle memory. When you create a variable, it is stored in a space in memory and this space has an address to identify the location of it and its value.

We can imagine memory as a set of lockers, where you store your things (variables) and the address as the number to identify the locker.

Finally, pointers!

So wtf are pointers? Pointers are just references to some space in memory that contains a variable a its values.

Analogy time! Pointers are like your locker key with the locker's number on it.

But, when we use pointers?

When you pass a variable to a function as a parameter, and your function receives that value, it doesn't receive the original variable but a copy.

// Here is a small example in C

// This function gonna receives the copy value
void change_x_value(int x) 
{
    x = 5;
}

int main()
{
    int x = 2;

    printf("Variable before change: %i\n", x);

    change_x_value(&x);

    printf("Variable after change: %i\n", x);
}

// RESULT:
 "Variable before change: 2"
 "Variable after change: 2"
Enter fullscreen mode Exit fullscreen mode

So if you want to change the value of the parameters received directly, you just can't. The solution is to pass a pointer (you are just passing a variable that stores an address/reference) as a parameter to the function that tells exactly where the real value is stored in the memory.


// This function gonna receives the pointer
// to the variable x and its value 
void change_x_value(int* x)
{
    // * symbol set and get the x variable value 
   // at the specified address
    x* = 5;
}

int main()
{
    int x = 2;

    printf("Variable before change: %i\n", x);

// Now I am passing the pointer (just an address) to the function
    change_x_value(&x); // & symbol just get the address of this variable

    printf("Variable after change: %i\n", x);
}

// RESULT:
 "Variable before change: 2"
 "Variable after change: 5"
Enter fullscreen mode Exit fullscreen mode

End

Did you see it? It's easy peasy lemon squeezy, don't need to be afraid of pointers anymore.

Top comments (0)