Q: How can I return multiple values from a function?
A: There are several ways of doing this. (These examples show hypothetical polar-to-rectangular coordinate conversion functions, which must return both an x and a y coordinate.)
#include <math.h>
polar_to_rectangular(double rho, double theta,
double *xp, double *yp)
{
*xp = rho * cos(theta);
*yp = rho * sin(theta);
}
...
double x, y;
polar_to_rectangular(1., 3.14, &x, &y);
struct xycoord { double x, y; };
struct xycoord
polar_to_rectangular(double rho, double theta)
{
struct xycoord ret;
ret.x = rho * cos(theta);
ret.y = rho * sin(theta);
return ret;
}
...
struct xycoord c = polar_to_rectangular(1., 3.14);
polar_to_rectangular(double rho, double theta,
struct xycoord *cp)
{
cp->x = rho * cos(theta);
cp->y = rho * sin(theta);
}
...
struct xycoord c;
polar_to_rectangular(1., 3.14, &c);
(Another example of this technique is the Unix system call stat.)
See also questions 2.7, 4.8, and 7.5a.