Pointers & Functions (Pass by Reference)
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.
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.
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:
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;
}
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.
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.
Write a swap function using pointers and use it to swap two integers declared in main.
#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;
}