Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 135 ยท Pointers

Pointers and Functions

Use pointers with C functions - swap values, return several results through out-parameters, return pointers safely, avoid dangling pointers and understand restrict.

C passes every argument by value: a function receives copies of the values you give it, and anything it does to its parameters stays inside the function. That's simple and safe, but it raises obvious questions. How does a function swap two of your variables? How does it give back two results when it can only return one? How does scanf store a number into your variable? The answer each time is a pointer: pass the address of the variable, and the function can reach the original through it.

Pointers also flow the other way. Functions return pointers to found elements, to buffers you provided, or to freshly allocated memory, and that's where one of C's classic bugs lives: returning the address of a local variable that no longer exists. This lesson covers both directions: out-parameters and in/out parameters, safe and unsafe pointer returns, and the C99 restrict qualifier, which lets a function promise that its pointers don't overlap.

If you haven't yet, read Parameters and Return Values for the basics of passing by value.

Swapping two variables

Swapping is the classic demonstration. The first version below receives copies, swaps them, and throws them away. The second receives addresses and swaps the originals:

C swap that fails and swap that works

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Inside swap, a and b are still copies, but they're copies of addresses. Both copies point at the caller's variables, so *a = *b writes to left. The call site makes it visible: swap(&left, &right) with & tells anyone reading the code that the function may change those variables.

Notice that swap(&x, &x) still works with this implementation (the value is saved in tmp first). The well-known "XOR swap" trick that avoids a temporary does not: with both pointers equal, it sets the value to 0. Keep the temporary; compilers optimize it perfectly well.

Out-parameters: returning more than one value

A function has only one return value, but it can fill in as many variables as you give it pointers to. These pointer parameters are called out-parameters. A common convention is to return a status (success or failure) and deliver the actual results through out-parameters, exactly like scanf returns a count and stores the numbers through the pointers you pass.

C Results through out-parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Some conventions that make out-parameters pleasant to use:

  • Put inputs first and outputs last in the parameter list, as divide and min_max do. (The standard library isn't consistent here; memcpy and strcpy put the destination first.)
  • Return a status, not a result, when the operation can fail. A bool or an error code tells the caller whether the out-values are valid. If divide fails, q and r are left untouched.
  • Allow NULL for optional outputs when callers may not need every result, and document it. min_max checks each pointer before writing through it.
  • Don't read an out-parameter before the function sets it. lowest is uninitialized until min_max succeeds.

In/out parameters

A pointer parameter can also be read and written: the function uses the current value and updates it. These in/out parameters are common for counters, cursors and state that a function advances. Here's a function that consumes one number from a string and moves the caller's position forward (you saw the double-pointer version of this idea in Pointers to Pointers):

C An in/out position parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

(*pos)++ increments the caller's pos; the parentheses are required, because *pos++ would move the pointer and leave the count alone. This digit loop is fine for a demo, but it doesn't detect overflow. For real input, use strtol from Converting Strings and Numbers.

Pointers to structs

The same mechanism lets you pass a big struct without copying it: pass a pointer, and use const if the function only reads it. You'll do this constantly once you meet Structures and Pointers. Small structs can also simply be returned by value, which is often clearer than an out-parameter.

Returning pointers

A function can return a pointer, as long as the thing it points to still exists after the function returns. There are exactly four safe sources:

  1. Memory the caller passed in, such as an element of the caller's array or the caller's buffer.
  2. Static storage: a string literal, a global, or a static local variable. It lives for the whole program.
  3. Heap memory from malloc, which lives until someone calls free.
  4. A null pointer, meaning "nothing", which the caller must check.
C Three safe ways to return a pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each case has an implicit contract that you should spell out in a comment:

  • largest returns a pointer that's valid only as long as the caller's array is.
  • weekday_name returns read-only text the caller must not free or modify, hence const char *.
  • repeat_text returns memory the caller owns and must free. Forgetting that is a memory leak; Dynamic Memory covers allocation in depth.

A pointer to a static local buffer is the trickiest case. Some old library functions, like strerror, asctime and localtime, return a pointer to an internal static buffer that the next call overwrites. Two calls in one printf can print the same text twice, and the functions aren't safe to call from multiple threads at once. That's why newer alternatives such as strftime or POSIX localtime_r take a caller-provided buffer instead.

The caller-provided buffer pattern

Letting the caller pass in the destination solves the ownership question neatly: the caller decides where the memory lives and how big it is, and the function returns that same pointer for convenience, as fgets, strcpy and strcat do.

C
/* Writes "Last, First" into buffer and returns buffer. */
char *format_name(char *buffer, size_t size, const char *first, const char *last) {
    snprintf(buffer, size, "%s, %s", last, first);
    return buffer;
}

char name[64];
printf("%s\n", format_name(name, sizeof name, "Ada", "Lovelace"));   /* Lovelace, Ada */

The dangling pointer trap

A local variable lives on the stack only while its function runs. When the function returns, that storage is reused for the next function call. Returning its address gives the caller a dangling pointer: a pointer to memory that no longer holds the object. Reading through it is undefined behavior. It might show the old value, a different value, or crash, and the result can change with the compiler, the optimization level, or an unrelated edit.

This example compiles with a warning on purpose. The broken function is never called, so the output doesn't depend on undefined behavior; the point is the compiler's message:

C Returning the address of a local

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC reports warning: function returns address of local variable [-Wreturn-local-addr] and points at return buffer;. In fact, GCC goes further: since dereferencing that pointer could never be valid, it compiles the broken function to return a null pointer, so a caller that used it would most likely crash. Other compilers behave differently. Either way, the fix is one of the four safe sources above: a caller buffer (as shown), a static buffer, or malloc.

The compiler can only catch the simplest cases. These dangle too, and usually compile without any warning:

  • Storing the address of a local in a global variable or a struct that outlives the function.
  • Keeping a pointer into a block of heap memory after free, or after realloc moved it.
  • Returning a pointer into a local array through an out-parameter (*out = local_array;).

Memory Errors shows tools like AddressSanitizer that detect these at run time.

Tip: Returning a struct by value is often the cleanest way to give back several values or a small fixed-size string: struct name_tag { char text[32]; }; struct name_tag make_tag(void); copies the whole array to the caller, with no lifetime questions at all.

restrict: promising pointers don't overlap

When a function receives two pointers, the compiler normally has to assume they might point to the same memory. That assumption, called aliasing, limits optimization. Look at this function and what happens when both arguments point to the same variable:

C When two pointers alias

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The separate call gives 21. The aliased call gives 4, not 3, because the first addition also changed *amount, and the compiler correctly re-reads it. To produce that correct answer, the compiler must reload *amount after every write to *target, even in the common case where they never overlap.

C99 added the restrict qualifier so you can promise otherwise. Declaring a parameter int *restrict target says: "for the duration of this function, the memory reached through target is accessed only through target". With that promise, the compiler can load *amount once and keep it in a register.

C
void add_twice(int *restrict target, const int *restrict amount);

void scale(size_t n, double *restrict out, const double *restrict in, double factor) {
    for (size_t i = 0; i < n; i++) {
        out[i] = in[i] * factor;      /* free to vectorize: out and in don't overlap */
    }
}

The promise is yours to keep. Calling the restrict version as add_twice(&x, &x) is undefined behavior, and it might print 3, 4 or anything else. GCC's -Wrestrict warning (part of -Wall) catches obvious cases such as passing the same variable to two restrict parameters, but most violations go unnoticed.

The standard library uses restrict to document which functions can't handle overlap:

Function Prototype (simplified) Overlapping buffers
memcpy void *memcpy(void *restrict dest, const void *restrict src, size_t n) undefined behavior
memmove void *memmove(void *dest, const void *src, size_t n) allowed, copies correctly
strcpy char *strcpy(char *restrict dest, const char *restrict src) undefined behavior
printf int printf(const char *restrict format, ...) (format and arguments)

So when you shift elements inside one array, for example to delete an item, use memmove, never memcpy. Use restrict in your own code mainly for performance-critical functions working on separate arrays, and only when you're sure every caller respects it. (C++ has no standard restrict; see C and C++.)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? void f(int n) { n = 99; } then int x = 5; f(x); printf("%d", x);

    f receives a copy of x, so assigning to n changes only the copy. To change x, f would need an int * parameter and the call f(&x).
  2. 2. Which function signature lets a function report failure and also deliver two integer results?

    The bool return value is the status, and the two pointer parameters are out-parameters the function writes through. Returning a local array would create a dangling pointer.
  3. 3. Which of these functions returns a pointer that is safe to use after the call?

    A string literal has static storage and lives for the whole program. The other three return addresses of local variables, which die when the function returns.
  4. 4. Without restrict, void add_twice(int *t, const int *a) { *t += *a; *t += *a; } is called as int x = 2; add_twice(&x, &x);. What is x?

    The pointers alias, which is legal without restrict. The first line makes x 4, and the second adds the new value of *a, so x becomes 8.
  5. 5. You need to shift the elements of one array one position to the left. Which function is correct?

    memcpy's parameters are restrict-qualified, so overlapping buffers are undefined behavior. memmove is specified to handle overlap correctly.

Summary

  • Arguments are copies; to let a function change a caller's variable, pass its address (swap(&a, &b)) and write through the pointer.
  • Out-parameters deliver extra results; return a status (bool or an error code), put outputs last, and allow NULL for optional outputs if you document it.
  • In/out parameters are read and updated, like a position or a counter: (*pos)++.
  • Return pointers only to things that outlive the call: caller memory, static storage, heap memory (the caller frees it), or NULL.
  • Returning the address of a local creates a dangling pointer. GCC warns with -Wreturn-local-addr, but many dangling cases go undetected.
  • Caller-provided buffers (char *f(char *buf, size_t size, ...)) avoid ownership and lifetime problems.
  • restrict (C99) promises that a pointer is the only way to reach its memory, enabling optimizations. Breaking the promise is undefined behavior; that's why memcpy can't handle overlap and memmove can.

Next: Dynamic Memory: malloc, calloc, realloc and free