eve*_*veo 2 c return argument-passing
main如果所述函数已经具有返回值,如何将函数的局部变量传回?对不起,这个问题,我试图让每个人尽可能客观,而不仅仅是我的情况.
具体来说:我有一个叫做的函数subtotal.有两个计数变量.其中一个我回来了return.另一个我需要提供我的main()功能使用.
编辑:澄清:
function something() {
float counter = 0.0;
int someOtherVar = 0;
// the work
return someOtherVar;
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是将counter浮动传递给main.
Mat*_*Mat 11
将所有返回值放入a中struct,然后返回.
#include <stdio.h>
struct myret {
int total;
int count;
};
struct myret foo(void)
{
struct myret r;
r.total = 42;
r.count = 2;
return r;
}
int main(void)
{
struct myret r = foo();
printf("%d %d\n", r.total, r.count);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者使用"其他"返回值的指针.
int foo(int *other)
{
if (other)
*other=42;
return 1;
}
int main(void)
{
int a = 0;
int b = foo(&a);
...
}
Run Code Online (Sandbox Code Playgroud)
您还可以通过将指向结构的指针传递给函数来组合它们,并让您的函数填充:
#include <stdio.h>
struct myret {
int total;
int count;
};
int foo(struct myret *r)
{
if (r) {
r->total = 42;
r->count = 2;
}
return 0;
}
int main(void)
{
struct myret r;
int rc = foo(&r);
if (rc == 0) {
printf("%d %d\n", r.total, r.count);
}
return rc;
}
Run Code Online (Sandbox Code Playgroud)
将指向额外返回值的指针作为参数传递给函数.
int foo(int *anotherOutParam)
{
*anotherOutParam = 1;
return 2;
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
int ret1, ret2;
ret1 = foo(&ret2);
//do something with ret2
Run Code Online (Sandbox Code Playgroud)
通常,@ Mat建议将所有返回值打包成a struct.
| 归档时间: |
|
| 查看次数: |
1584 次 |
| 最近记录: |