Pointers and Functions

In Module 6 we saw that a function gets a copy of each value, so it can't change the original. This swap function does not work:

#include <stdio.h>

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

int main() {
    int x = 1;
    int y = 2;
    badSwap(x, y);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

Output

x = 1, y = 2

Nothing changed! The function swapped its own copies. The fix: pass the addresses, and let the function change the values at those addresses:

#include <stdio.h>

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

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

Output

x = 2, y = 1

Think of it like this: Giving a function a copy is like giving a builder a photo of your house – they can paint the photo, but your house stays the same. Giving them the address lets them go to the real house and paint it.

Returning more than one result

A function can only return one value. With pointers it can fill in several:

#include <stdio.h>

void minMax(int *arr, int size, int *smallest, int *biggest) {
    *smallest = arr[0];
    *biggest = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] < *smallest) {
            *smallest = arr[i];
        }
        if (arr[i] > *biggest) {
            *biggest = arr[i];
        }
    }
}

int main() {
    int nums[5] = {7, 2, 9, 4, 5};
    int lo, hi;
    minMax(nums, 5, &lo, &hi);
    printf("Smallest %d, biggest %d\n", lo, hi);
    return 0;
}

Output

Smallest 2, biggest 9

Tip: Now you know why scanf needs &: it is a function that must change your variable, so it needs the variable's address.

HOME LABS COMMUNITY DASHBOARD