Lesson 2 of 3 · Pointers · 2 min read · Updated
Changing a caller's variable
The first thing pointers actually buy you — functions that can change what you gave them.
You saw that a function cannot change the variable you passed it, because it only gets a copy. Pass the address instead, and it can.
#include <stdio.h>
void double_it(int *n)
{
*n = *n * 2;
}
int main(void)
{
int x = 21;
double_it(&x);
printf("%d\n", x); /* 42 */
return 0;
}
The classic: swapping two values
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
int x = 1, y = 2;
swap(&x, &y);
printf("%d %d\n", x, y); /* 2 1 */
return 0;
}
Note
Without pointers this function is impossible to write in C. That is why swap is the example every C course reaches for — it is the smallest problem that genuinely needs them.
Returning more than one answer
/* A function can only return one value —
pointers let it deliver several. */
void min_and_max(int arr[], int n, int *min, int *max)
{
*min = arr[0];
*max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] < *min) *min = arr[i];
if (arr[i] > *max) *max = arr[i];
}
}
Warning
A pointer that points nowhere useful is the most common source of crashes in C. Set a pointer to NULL when it has no target, and check for NULL before dereferencing. Dereferencing NULL crashes the program — which, honestly, is better than the alternative of silently corrupting memory.
Why must swap take int *a rather than int a?
Create a free account to save your progress, or sign in.