Thuta Learning
C
ExercisesProgrammingBeginner

Exercises: Functions & Pointers Practice

CLesson 3450 min

What you'll walk away with

  • Write a recursive function with a correct base case and a known overflow limit
  • Return a pointer into the caller's array, and NULL when there is no answer
  • Change a caller's variables through pointer parameters
  • Decide when to pass a struct by value, by pointer or by const pointer
  • Return a malloc'd array and state who must free it

Explain it simply

Explain it simply

This exercise set combines functions with pointers. In the fundamentals set a function could only hand back one value with return. Here functions also reach back into the caller: swap() changes two of main's variables, find_max() returns the address of an element inside main's array, and birthday() edits a struct that belongs to main.

A pointer parameter is like giving someone your home address instead of a photo of your home. With the photo they can look, but anything they draw on it changes only their copy. With the address they can walk in and move the furniture. Every pointer parameter is a decision about which of the two you are handing over.

Problem → Why → Solution

The problem: the swap that changes nothing

Almost everyone's first swap looks like the code below. It compiles without a warning even under -Wall -Wextra, runs without crashing, and prints x = 5, y = 10, exactly the values it started with. The function did swap something: its own copies of the arguments, which disappear the moment it returns.

The same misunderstanding causes subtler bugs. A function that returns the address of one of its own local variables compiles too, and may even print the right value once, because that memory has not been reused yet. Then another call overwrites it and the value changes behind your back.

swap_by_value.c
#include <stdio.h>

void swap(int a, int b) {        /* receives copies of x and y */
    int tmp = a;
    a = b;
    b = tmp;                     /* only the copies are swapped */
}

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

Why C behaves this way

C passes every argument by value: the function receives a copy, whether it is an int, a struct or a pointer. To let a function change the caller's variable, you pass a copy of its address, and the function writes through that address with *. The address itself is still a copy, but it leads back to the original variable.

Core concept: what a pointer parameter promises

Before writing a function that takes or returns a pointer, decide its contract: who owns the memory, whether the function may change it, how long the pointer stays valid, and what happens when there is no answer. The four tasks each practise one part of that contract.

SignatureWhat it tells the caller
void swap(int *a, int *b)In/out: reads both values and writes new ones through the pointers
int *find_max(int arr[], size_t size)Returns an address inside your array, or NULL when size is 0
void print_student(struct Student s)Gets a private copy, so your struct cannot change
void birthday(struct Student *s)May modify your struct through s
int *copy_above(..., size_t *out_n)Returns new heap memory you must free; the length comes back through out_n

Pointers returned from a function deserve the most care. A pointer into the caller's array is fine, because that array outlives the call. A pointer to the function's own local variable is never fine: the local stops existing at return, and the pointer dangles. Heap memory from malloc survives the return, but then the caller becomes its owner and must free it exactly once.

Recursion has its own contract. factorial(n) calls factorial(n - 1) until it reaches the base case n <= 1; without that case the calls never stop and the program runs out of stack. Every recursive function should also state its valid input range: n! grows so fast that 13! no longer fits in a 32-bit int and 21! does not fit in a 64-bit long long.

Finally, struct parameters. Passing by value copies every byte, which is fine for a small struct and guarantees the function cannot change yours. For larger structs, or when the function only reads, const struct Student *s avoids the copy and still promises not to modify it.

Mental model: copy of a value or of an address
  1. Every argument arrives as a copy
  2. Copy of a value: the caller is safe
  3. Copy of an address: writes reach caller
  4. A returned address must outlive the call

When a function returns a pointer, ask what it points to and who keeps that object alive.

General pattern

c
void update(T *target);                 /* may change the caller's T      */
void inspect(const T *source);          /* reads only, no copy            */
T *find(T arr[], size_t n);             /* address inside arr, or NULL    */
T *create(size_t n, size_t *out_len);   /* heap result: the caller frees  */

/* call sites */
update(&value);
T *hit = find(items, count);
if (hit != NULL) { /* use *hit */ }

Read a pointer signature as a promise: a plain T * may write, const T * only reads, and a returned pointer either points into something the caller already owns or hands ownership of new memory to the caller. Always check a returned pointer for NULL before dereferencing it.

The four tasks, solved with their edge cases

Each task is a function, and main() drives it with cases that test the contract rather than only the happy path: 20! and 21! for the factorial limit, a tie and an empty array for find_max, swapping a variable with itself, and a struct passed both ways. The program prints positions (top - scores) rather than raw addresses, because addresses change from run to run.

functions_pointers.c
#include <stddef.h>
#include <stdio.h>

struct Student {
    char name[30];
    int age;
    float gpa;
};

/* Task 1: n! for 0..20. Returns -1 when there is no valid answer. */
long long factorial(int n) {
    if (n < 0 || n > 20) {
        return -1;                     /* 21! does not fit in 64 bits */
    }
    if (n <= 1) {
        return 1;                      /* base case */
    }
    return n * factorial(n - 1);       /* recursive case */
}

/* Task 2: address of the largest element (first one on a tie), NULL if empty. */
int *find_max(int arr[], size_t size) {
    if (size == 0) {
        return NULL;
    }
    int *best = &arr[0];
    for (size_t i = 1; i < size; i++) {
        if (arr[i] > *best) {
            best = &arr[i];
        }
    }
    return best;
}

/* Task 3: exchange two ints through their addresses. */
void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

/* Task 4: by value, so the function works on its own copy. */
void print_student(struct Student s) {
    printf("%s, age %d, GPA %.2f\n", s.name, s.age, s.gpa);
}

void birthday_copy(struct Student s) { s.age++; }    /* changes the copy only */
void birthday(struct Student *s) { s->age++; }       /* changes the caller's */

int main(void) {
    printf("Task 1:");
    for (int n = 1; n <= 10; n++) {
        printf(" %lld", factorial(n));
    }
    printf("\n        20! = %lld, 21! -> %lld\n", factorial(20), factorial(21));

    int scores[] = {64, 91, 78, 91};
    size_t size = sizeof scores / sizeof scores[0];
    int *top = find_max(scores, size);
    printf("Task 2: max %d at index %td\n", *top, top - scores);
    *top = 100;                        /* writes into the array itself */
    printf("        scores[1] is now %d\n", scores[1]);
    printf("        empty array -> %s\n", find_max(scores, 0) ? "found" : "NULL");

    int x = 5, y = 10;
    swap(&x, &y);
    printf("Task 3: x = %d, y = %d\n", x, y);
    swap(&x, &x);
    printf("        swap(&x, &x) leaves x = %d\n", x);

    struct Student s1 = {"Aung Aung", 20, 3.75f};
    printf("Task 4: ");
    print_student(s1);
    birthday_copy(s1);
    printf("        after birthday_copy: age %d\n", s1.age);
    birthday(&s1);
    printf("        after birthday:      age %d\n", s1.age);
    return 0;
}

Code breakdown

  1. Base case and recursive casereturn n * factorial(n - 1);

    Each call waits for factorial(n - 1) and multiplies the answer by n. The chain ends at n <= 1, which returns 1. The n > 20 guard above it returns -1 because 21! is larger than the biggest long long.

  2. Remember where, not whatint *best = &arr[0];

    best remembers where the largest element lives. Because the comparison is >, a later equal value does not replace it, so in the tie between the two 91s the first one, at index 1, wins.

  3. Pointer subtraction for the indexprintf("Task 2: max %d at index %td\n", *top, top - scores);

    Subtracting two pointers into the same array gives the distance in elements, of type ptrdiff_t, which %td prints. *top reads the value stored at that address.

  4. Writing through the returned pointer*top = 100;

    find_max returned an address inside scores, so writing through it changes scores[1] itself. That is the difference between returning a pointer and returning a copy of the value.

  5. Swap through addressesint tmp = *a;

    tmp holds the first value while *a takes the second. Because the swap goes through a temporary, swap(&x, &x) is harmless; the XOR trick without a temporary would turn x into 0 in that case.

  6. Copy versus pointervoid birthday(struct Student *s) { s->age++; }

    birthday_copy increments the age in its own copy, so main still sees 20. birthday receives the address, and s->age++ (short for (*s).age++) changes main's struct to 21.

You should see
Task 1: 1 2 6 24 120 720 5040 40320 362880 3628800
        20! = 2432902008176640000, 21! -> -1
Task 2: max 91 at index 1
        scores[1] is now 100
        empty array -> NULL
Task 3: x = 10, y = 5
        swap(&x, &x) leaves x = 10
Task 4: Aung Aung, age 20, GPA 3.75
        after birthday_copy: age 20
        after birthday:      age 21

Why returning a local's address is a trap

GCC catches the obvious version. Compiling a function that ends in return arr; where arr is a local array prints "warning: function returns address of local variable [-Wreturn-local-addr]" even without optimisation.

The address can travel through another variable first, though. For a function that sets int *best = &nums[0] on a local nums array and later returns best, GCC 16 warned "function may return address of local variable" only once optimisation was turned on with -O2, and said nothing at the default -O0. Compiler warnings are a safety net with holes, not a proof. The reliable fix is the rule itself: return pointers only into memory the caller owns, or into heap memory you hand over.

In real projects

In real projects

These patterns are the everyday vocabulary of C libraries. The standard library's strchr returns a pointer into the string you passed, or NULL when the character is missing, exactly like find_max. sscanf and strtol return results through pointer parameters, and functions such as POSIX getline, or strdup (standard since C23), hand back heap memory with a documented rule that the caller frees it.

In a larger code base the contract is written in the header next to each prototype: whether a pointer may be NULL, whether the function keeps it, and who frees what it returns. A resizable inventory module, for example, might offer inventory_add(Inventory *inv, ...), inventory_find(const Inventory *inv, ...) returning a pointer into its own array, and inventory_free(Inventory *inv). Its documentation must also say that the pointer from inventory_find is valid only until the next add, because realloc may move the array.

Common mistakes

Common mistakes

Dereferencing a NULL result

find_max returns NULL for an empty array. printf("%d", *find_max(scores, 0)) dereferences NULL, which usually crashes. Store the result, check it, then use it.

Returning the address of a local

A local array or variable ends its life when the function returns. Return a pointer into an array the caller passed in, or allocate with malloc and document that the caller frees it.

Computing factorial in int with no limit

factorial(13) needs 6,227,020,800, beyond a 32-bit int's 2,147,483,647. Signed overflow is undefined behaviour; in a test with GCC the int version printed 1932053504, a believable but wrong number. Choose a wider type and reject inputs past its limit.

Keeping pointers into an array that may move

After realloc grows an array, pointers to its old elements may point into freed memory. Fetch them again after any operation that can reallocate.

Mini challenge

Output parameters, in-place changes and heap results

Write three functions that each return their result in a different way: min_max() through output parameters, reverse() by changing the caller's array in place, and copy_above() by returning a new heap array whose length comes back through a pointer. Test each with normal data, an empty array and a single element.

  • min_max(const int *a, size_t n, int *min, int *max) returns 0 for an empty array
  • reverse(int *a, size_t n) swaps with two pointers and is safe when n is 0 or 1
  • copy_above() returns NULL with *out_n = 0 when nothing is above the limit
  • main() frees every array that copy_above() returns
pointer_results.c
#include <stdio.h>
#include <stdlib.h>

int min_max(const int *a, size_t n, int *min, int *max) {
    // TODO: return 0 when n == 0; otherwise write the extremes through min, max
}

void reverse(int *a, size_t n) {
    // TODO: only when n >= 2: left = a, right = a + n - 1, swap, move inward
}

int *copy_above(const int *a, size_t n, int limit, size_t *out_n) {
    // TODO: count the matches, malloc exactly that many, copy them in,
    //       set *out_n; return NULL (and *out_n = 0) when there are none
}

int main(void) {
    int data[] = {4, 9, -2, 7, 9};
    // TODO: print min and max, then try min_max on an empty array
    // TODO: reverse data and a one-element array, print both
    // TODO: copy_above(data, ..., 5, ...) and with limit 100; free the results
}

Expected: min -2, max 9; the empty array reports no min or max; data reversed is 9 7 -2 9 4 and the one-element array stays 42; above 5 gives 9 7 9, and above 100 gives (none).

Show hint

Output parameters are written with *min = a[0]; and read by the caller after passing &lo. For reverse, compare the pointers themselves (while (left < right)). In copy_above, a first loop counts the matches so that a single malloc(matches * sizeof *result) is exactly the right size.

Show solution
pointer_results.c
#include <stdio.h>
#include <stdlib.h>

/* 0 for an empty array; otherwise stores the smallest and largest, returns 1. */
int min_max(const int *a, size_t n, int *min, int *max) {
    if (n == 0) {
        return 0;
    }
    *min = a[0];
    *max = a[0];
    for (size_t i = 1; i < n; i++) {
        if (a[i] < *min) {
            *min = a[i];
        }
        if (a[i] > *max) {
            *max = a[i];
        }
    }
    return 1;
}

/* Reverses a[0..n-1] in place with two pointers walking toward each other. */
void reverse(int *a, size_t n) {
    if (n < 2) {
        return;                        /* also keeps a + n - 1 from going below a */
    }
    int *left = a;
    int *right = a + n - 1;
    while (left < right) {
        int tmp = *left;
        *left = *right;
        *right = tmp;
        left++;
        right--;
    }
}

/* New heap array holding the values above limit; *out_n gets its length.
   NULL (with *out_n = 0) when nothing matches or malloc fails.
   The caller owns the result and must free() it. */
int *copy_above(const int *a, size_t n, int limit, size_t *out_n) {
    *out_n = 0;
    size_t matches = 0;
    for (size_t i = 0; i < n; i++) {
        if (a[i] > limit) {
            matches++;
        }
    }
    if (matches == 0) {
        return NULL;
    }
    int *result = malloc(matches * sizeof *result);
    if (result == NULL) {
        return NULL;
    }
    size_t j = 0;
    for (size_t i = 0; i < n; i++) {
        if (a[i] > limit) {
            result[j++] = a[i];
        }
    }
    *out_n = matches;
    return result;
}

void print_array(const char *label, const int *a, size_t n) {
    printf("%s:", label);
    for (size_t i = 0; i < n; i++) {
        printf(" %d", a[i]);
    }
    if (n == 0) {
        printf(" (none)");
    }
    printf("\n");
}

int main(void) {
    int data[] = {4, 9, -2, 7, 9};
    size_t n = sizeof data / sizeof data[0];
    int lo, hi;

    if (min_max(data, n, &lo, &hi)) {
        printf("min %d, max %d\n", lo, hi);
    }
    if (!min_max(data, 0, &lo, &hi)) {
        printf("empty: no min or max\n");
    }

    reverse(data, n);
    print_array("reversed", data, n);
    int one[] = {42};
    reverse(one, 1);
    print_array("one element reversed", one, 1);

    size_t count;
    int *big = copy_above(data, n, 5, &count);
    print_array("above 5", big, count);
    free(big);

    int *none = copy_above(data, n, 100, &count);
    print_array("above 100", none, count);
    free(none);                        /* free(NULL) is allowed and does nothing */
    return 0;
}

Quick quiz 1 / 3

find_max() returns a pointer into scores, and top points at index 1. After *top = 100;, what does printf("%d", scores[1]) print?

Quick quiz 2 / 3

Which function definition is a bug, even though it may compile?

Quick quiz 3 / 3

birthday_copy(s1) runs s.age++ on its parameter. If s1.age was 20, what is it afterwards?

What to remember

  • C passes every argument by value; pass an address to let a function change the caller's data
  • Return pointers only into the caller's memory or into heap memory the caller will free
  • Check a returned pointer for NULL before dereferencing it
  • Give recursion a base case and a documented input range (21! overflows long long)
  • Pass small structs by value, and larger read-only ones by const pointer

AddressSanitizer — LLVM/Clang

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercises: Functions & Pointers Practice | Thuta Learning