从C中的函数返回多个参数 [英] return more than one parameter from a function in C
问题描述
我一直在试图找出如何在那里我可以从一个函数用C返回多个值。
i have been trying to figure out ways where i can return more than one value from a function in C.
例如说我有
int compute(int a, int b)
{
int c;
// do some computation on a,b,c
// return a,b,c
}
现在我将这些值在数组中说了,我试图做到这一点,我然后我意识到,数组需要是动态的,因此它可以在被引用的main()也是如此。
now i can return these values say in an array, and i was trying to do that and i then i realized that the array needs to be dynamic so it can be referenced in main() as well.
另一种方式可能是我创建了一个结构,然后只返回结构变量。
Another way could be that i create a structure and then just return the struct variable.
是否有这样做的任何简单而强大的方式,除了上述工作周围的其他?我必须回到它们是相互独立的,从方法大约25不同的计算值,我在我的code已经有很多结构。
Is there any simple and robust way of doing this, other than the above work around ? i have to return about 25 different computation values which are independent of each other from a method, and i have a lot structs in my code already.
感谢您。
推荐答案
如果该值都逻辑上相关的,那么它是有道理的把它们放入一个结构。但是,如果你改变这种不紧耦合的只有几个值,就可以将它们作为这样的指针:
If the values are all logically related, then it makes sense to put them into a structure. But if you're changing only a few values that aren't tightly coupled, you can pass them as pointers like this:
int swap(int *a, int *b) {
int tmp;
if (a == b) { // Pointers are equal, so there's nothing to do!
return -1; // Indicate the values haven't changed.
}
tmp = *a;
*a = *b;
*b = tmp;
return 0; // Indicate the swap was successful.
}
void main(...) {
int first = 12;
int second = 34;
if (swap(&first, &second) == -1) {
printf("Didn't swap: %d, %\n", first, second);
} else {
printf("Swapped: %d, %d\n", first, second);
}
}
这是将数据放入该函数的参数,以及有函数返回一个值,以指示成功/失败,或一些其他条件相当标准的技术。\\
It's a fairly standard technique to put data into the function arguments, and have the function return a value to indicate success/failure, or some other condition.\
这篇关于从C中的函数返回多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!