Returning multiple values via pointers
What you'll learn: How to use pointers to allow a function to "hand back" more than one piece of data to the caller.
The one-return limit
In C, a function is like a vending machine: you press a button, and exactly one item falls out. Using the return keyword, you can send back a single integer, a single float, or a single character. But what if you need a function to calculate two things at once, like the area and the perimeter of a rectangle?
You can’t write return area, perimeter;—the compiler simply won't allow it. To solve this, we use pointers as "delivery boxes."
Pointers as delivery boxes
Think of pointers as empty boxes that the caller provides. Instead of the function trying to shove two items through the narrow "return" slot, the caller hands the function the addresses of two variables. The function then reaches out, finds those specific spots in memory, and drops the results directly into them.
When the function finishes, the caller finds that its local variables have been updated with the new values.
Implementation in C
To do this, we define the function parameters as pointers (using *). Inside the function, we "dereference" those pointers to assign the results.
#include <stdio.h>
// This function "returns" two values via pointers
void get_rectangle_stats(double width, double height, double *area, double *perimeter) {
// We use the asterisk to go to the address and store the result
*area = width * height;
*perimeter = 2 * (width + height);
}
int main() {
double my_area, my_perimeter;
// We pass the addresses of our variables using the & operator
get_rectangle_stats(5.0, 3.0, &my_area, &my_perimeter);
printf("Area: %.2f, Perimeter: %.2f", my_area, my_perimeter);
return 0;
}
In this example, get_rectangle_stats has a void return type because it doesn't use the standard return slot. Instead, it directly modifies my_area and my_perimeter back in the main function. This bypasses the "one-item" limit of the return statement entirely.
Key takeaway
By passing addresses (&variable) to a function, you allow that function to modify multiple variables in the caller's memory, effectively "returning" as many values as you need.