Pointers & Functions (Pass by Reference)

⚙️ C Language 🟢 Lesson 13 of 20 📅 2026 Edition
Lesson 7 showed that C passes variables to functions by value, meaning the function only gets a copy. Pointers solve this limitation, letting a function reach back and modify variables that live in the caller's scope — a technique called "pass by reference."
1Simulating Pass by Reference
C Language ▶ Run Code
void doubleValue(int *ptr) {
    *ptr = *ptr * 2;
}

int main() {
    int number = 5;
    doubleValue(&number);   // pass the ADDRESS of number
    printf("%d\n", number);      // 10 - the original variable actually changed!
    return 0;
}

Compare this directly to Lesson 7's tryToChange() example, which failed to modify the original variable. The only difference here is passing a pointer instead of the value itself.

2A Practical Use Case: Swapping Two Values
C Language ▶ Run Code
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5, y = 10;
    swap(&x, &y);
    printf("x=%d y=%d\n", x, y);   // x=10 y=5
    return 0;
}

Swapping two variables is impossible to do correctly with plain pass-by-value parameters in C — this is one of the classic, textbook examples of exactly why pointers exist.

3Returning Multiple Values from a Function

A C function can only return a single value directly. Pointers let you work around this by having the function write multiple results directly into variables the caller provides:

C Language ▶ Run Code
void getMinMax(int arr[], int size, int *min, int *max) {
    *min = *max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] < *min) *min = arr[i];
        if (arr[i] > *max) *max = arr[i];
    }
}

int main() {
    int nums[5] = {4, 8, 1, 9, 3};
    int min, max;
    getMinMax(nums, 5, &min, &max);
    printf("Min: %d Max: %d\n", min, max);
    return 0;
}
4Pointers to Pointers (Brief Overview)

A pointer can itself be pointed to by another pointer, written int **ptr. This sounds exotic, but you'll encounter it most often when a function needs to modify a pointer variable itself (not just the value it points to) — a topic worth revisiting once you're comfortable with single-level pointers.

⚠️ Common Mistake: Passing a Value Instead of an Address When a Pointer Is Expected

Calling doubleValue(number) instead of doubleValue(&number) when the function expects an int * parameter is a common compiler warning beginners ignore — the function will try to treat the number 5 itself as if it were a memory address, which causes a crash the moment it's dereferenced.

💻 Try It Yourself

Write a swap function using pointers and use it to swap two integers declared in main.

C Language ▶ Run Code
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 3, y = 8;
    printf("Before: x=%d y=%d\n", x, y);
    swap(&x, &y);
    printf("After: x=%d y=%d\n", x, y);
    return 0;
}
Run This in Our Compiler →