Two Results at Once
With return, a function gives back only one value. But some calculations have two results. For example, 135 minutes is 2 hours and 15 minutes: two numbers. With pointers, a function can store as many results as it needs in the caller's variables:
#include <stdio.h>
void split_time(int total_minutes, int *hours, int *minutes) {
*hours = total_minutes / 60;
*minutes = total_minutes % 60;
}
int main(void) {
int hours = 0;
int minutes = 0;
split_time(135, &hours, &minutes);
printf("%d h %d min\n", hours, minutes);
return 0;
}This prints:
2 h 15 minThe function only reads the first parameter, so it's an ordinary int, and you can pass it a number. It writes to the other two, so they are pointers, and you must pass them the addresses of variables. Such parameters are called output parameters: the function doesn't read them, it fills them in. The stars in the function's first line tell you which parameters are results.
The variables hours and minutes must exist before the call. Here they start at 0, and the function overwrites them. When you call the function again with the same variables, it overwrites them again. And as usual, when you forget the & in the call, compiling ends with an error that says take the address with &.
Instructions
- 1
In place of the comment, write a function
sharewith four parameters:candiesandchildrenof typeint, which it only reads, and the pointerseachandleft_overof typeint *, where it stores the results. The function shares the candies among the children: each child getscandies / childrencandies, andcandies % childrenare left over. - 2
In
main, belowprintf, create the variableseachandleft_overwith the value0. Callsharewithcandies,childrenand the addresses of the two new variables. Then printEach child: 3, left over: 2, with%dfor both numbers. - 3
One more child comes. Below the last
printf, add 1 tochildren, callshareagain with the same variables and print the result the same way. The program printsEach child: 2, left over: 5.