如何在 C 编程语言的一个函数中同时返回两个整数类型值,还是应该编写两个不同的函数?
3498 次
5 回答
5
您可以创建一个struct
有两个整数的 a,并将其struct
作为函数的结果返回。
在诸如 C 之类的语言中,您可以struct
像这样存储数据:
struct foo {
int x;
int y;
}
于 2015-08-08T10:56:28.250 回答
3
两个不同的函数或通过引用参数传递。
例如
void someFunc(int* outParam1, int* outParam2)
{
if (outParam1 != NULL) {
*outParam1 = 42;
}
if (outParam2 != NULL) {
*outParam2= 13;
}
}
于 2015-08-08T10:54:37.640 回答
3
如果返回它们不是强制性的并且您可以接受使用指针,它遵循一种可能的方法:
void your_function(/* some other parameters */ int *ret1, int *ret2) {
int first_value, second_value;
// do whatever you want there
*ret1 = first_value; // first_value is the first value you want to return, quite obvious
*ret2 = second_value; // still obvious
}
然后,您可以按如下方式调用它:
// somewhere
int r1, r2;
your_function(/* other parameters */ &r1, &r2);
// here you can use "returned" values r1, r2
于 2015-08-08T10:58:40.833 回答
1
在 C 中,函数只能返回一个值。您可以通过地址将变量传递给函数并使用函数对其进行修改。
#include <stdio.h>
int returnTwoInt(int *var2)
{
*var2 = 2;
return 1;
}
int main()
{
int var2 = 0;
int var1 = returnTwoInt(&var2);
printf("%d %d\n", var1, var2);
return 0;
}
于 2015-08-08T10:59:16.710 回答
1
您可以使用任何一种方式 -
使用struct
并返回struct variable
。
或者
使函数用指针处理参数。
前任-
void f1(int *x, int *y){
*x = 1;
*y = 2;
}
int main(int argc, char* argv[]) {
int x,y;
f1(&x, &y);
printf("%d %d",x,y);
return 0;
}
于 2015-08-08T11:01:47.630 回答