Course contentsShow
← C
Lesson 488 of 1,2197. PointersFree lesson

Modifying caller variables

Modifying caller variables

What you'll learn: How to use pointers to let a function "reach back" and change a variable belonging to the function that called it.

The problem: Functions are like islands

Normally, when you pass a variable into a function, C makes a copy of that value. Imagine you have a piece of paper with the number "10" written on it. If you give it to a function, C photocopies the paper and hands the copy to the function. If the function scribbles over the number or changes it to "20," your original piece of paper remains unchanged. This is called "Pass by Value."

But what if you actually want the function to update your original variable? To do that, you don't send the value; you send the address of where that variable lives in memory.

The solution: Passing the address

By passing a pointer as an argument, you are giving the function a map to your variable's house. Instead of working on a copy, the function uses the pointer to "reach back" into your local memory and change the value directly. This is often called "Pass by Reference."

In the code below, we use the & (address-of) operator when calling the function, and the * (dereference) operator inside the function to change the value at that address.

#include <stdio.h>

// This function takes a pointer to an integer
void addFive(int *numberPtr) {
    // Reach into the address and add 5 to the actual value
    *numberPtr = *numberPtr + 5;
}

int main() {
    int myScore = 10;

    printf("Before: %d\n", myScore); // Prints 10

    // Pass the ADDRESS of myScore using &
    addFive(&myScore);

    printf("After: %d\n", myScore);  // Prints 15!
    return 0;
}

Why this matters

Think of a GPS coordinate. If you give a friend the coordinates to your house, they can actually show up and paint your front door a different color. They aren't painting a photo of your house; they are changing the actual house because they know exactly where it is.

This is essential in C when you want a function to return more than one result, or when you want to modify a large structure without wasting time and memory making copies.

Key takeaway

To let a function modify a variable from the caller, pass the variable's address (&var) and use the dereference operator (*ptr) inside the function to update it.