prev up next   top/contents search

comp.lang.c FAQ 列表· 问题 20.1

Q我如何从函数中返回多个值?


A有几种方法可以做到这一点。(这些示例显示了假设的极坐标到直角坐标转换函数,它们必须同时返回 xx和 yy坐标。)

  1. 传递指向多个位置的指针,函数可以填充这些位置
    #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);
    
  2. 让函数返回一个包含所需值的结构
    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);
    
  3. 使用混合方法:让函数接受一个指向结构的指针,然后填充该结构
    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);
    
    (此技术的另一个示例是 Unix 系统调用 statstat.)
  4. 在紧急情况下,理论上你可以使用全局变量(尽管这很少是个好主意)。

另请参阅问题 2.74.87.5a


prev up next   contents search
关于此 FAQ 列表   关于 Eskimo   搜索   反馈   版权

Eskimo North 托管