Learn C · lesson 34 of 60 · about 8 minutes
Pointers and Functions
Split the free space and the next backup into MiB and KiB with one function that hands back two results through pointers.
What you'll learn
- Pass an address to a function
- Write a swap function
- Return several results through pointers
Two answers from one function
The report wants the free space and the next backup as MiB and KiB, like 2 MiB 372 KiB. A function can only return one value, so void split_kib(int kib, int *mib, int *rest) takes two addresses and writes its two answers through them: split_kib(free_kib, &mib, &rest);. Inside, a negative size is set to 0 first. That only changes the function's own copy of kib: the caller's free_kib stays as it was, because only mib and rest were passed by address.
Solving the copy problem
Functions receive copies of their arguments, so void add_bonus(int s) can't change the caller's score. Pass the address instead:
void add_bonus(int *s) { *s += 10; } called as add_bonus(&score);
Now the function follows the pointer straight to the caller's variable. This is exactly why scanf needs &.
The classic swap
#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("x=%d y=%d\n", x, y);
return 0;
}Output
x=2 y=1Returning two results
#include <stdio.h>
void split_time(int total, int *minutes, int *seconds) {
*minutes = total / 60;
*seconds = total % 60;
}
int main(void) {
int m, s;
split_time(135, &m, &s);
printf("%d min %d s\n", m, s);
return 0;
}Output
2 min 15 sNow try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.