如何在c中返回多值形式的函数? [英] how to return multi value form a function in c?

查看:58
本文介绍了如何在c中返回多值形式的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有和函数计算

无效阈值(float * output1,float * output2,int e,int y)

{



}

i希望这两个数组n两个整数返回主函数.can有人帮吗?

I have and function which calculate the
void threshold(float *output1,float *output2,int e, int y)
{

}
i want this two array n two integer to return to the main function .can anyone help?

推荐答案

您只能从任何函数返回单个值,但该值可以是指针。因此,如果您将两个整数封装在 struct 中,那么您可以返回指向结构的指针,从而返回多个值。



但是......小心!

有三种方法可以返回值:

You can only return a single value from any function, but that value can be a pointer. So if you "encapsulate" your two integers in a struct, then you can return a pointer to the struct and thus the multiple values.

But...be careful!
There are three ways to return the value:
myStruct* threshold(float *output1,float *output2,int e, int y)
{
myStruct ms;
...

return &ms;
}



这很糟糕,因为你创建的myStruct实例是在teh堆栈上分配的,当你退出函数时会释放内存。它被称为悬挂参考,它可能会导致一些可怕的间歇性问题!




This is bad, as the myStruct instance you create is allocated on teh stack, and the memory is deallocated when you exit the function. It's called a "hanging reference" and it can cause some horrible intermittent problems!

myStruct* threshold(float *output1,float *output2,int e, int y)
{
myStruct* pms = (myStruct*) malloc(sizeof(myStruct));
...

return pms;
}



这样可行,并且不会导致代码问题,但是您需要使用代码来释放内存,否则您的应用会导致内存泄漏并且使用越来越多的内存,直到它耗尽并崩溃。




This works, and doesn't cause code problems, but you need to have code to deallocate the memory, or your app will cause "memory leaks" and use more and more memory until it runs out and crashes.

myStruct ms;
myStruct* threshold(float *output1,float *output2,int e, int y)
{
...

return &ms;
}

这也有效,但您需要注意,myStruct只有一个实例,所以如果再次调用阈值,任何先前的整数值都将被覆盖。 />


更好的解决方案可能是将指向两个整数的指针传递给函数,并直接修改它们而不是返回值:

This also works, but you need to be aware that there is only ever one instance of teh myStruct, so if you call threshold again, any previous integer values will be overwritten.

The better solution may be to pass pointers to two integers into the function, and modify those directly instead of returning a value:

void threshold(float *output1,float *output2,int e, int y, int *px, int *py)
{
myStruct ms;
...
*px = ms.X;
*py = ms.Y;
}


这篇关于如何在c中返回多值形式的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆