如何传递函数之间的阵列 [英] how to pass arrays between functions

查看:91
本文介绍了如何传递函数之间的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能帮助我吗?我具有一个C程序的问题。在这里,它是:

Can someone help me? I having a problem with a C program. Here it is:

在我主我调用一个函数(FUNC A),其中两个参数是第二个函数(FUN B)和用户数据(即在原则上可以是单号,char或数组)。这种用户数据也是函数B.我所拥有的一切工作时,用户数据是一个整数,但现在我需要把它作为一个数组的参数。因此,present工作结构是这样的:

In my main I call a function (func A) where two of the arguments are a second function (fun B) and "user data" (that in principle can be a single number, char or array). This "user data" is also an argument of the function B. I have everything working when the "user data" is a single integer but now I need to use it as an array. So the present working structure is like this:

static int FunB(...,void *userdata_)  
{  
   int *a=userdata_;  
   ...  
   (here I use *a that in this case will be 47)  
   ...  
}  

int main()  
{  
   int b=47;  
   funcA(...,FunB,&b)  
}  

所以现在我想在MAIN B作为数组(例如{3,45})以传递更多一个单一的数据到函数B

So now I want b in the main as an array (for example {3,45} ) in order to pass more that one single "data" to the function B.

感谢

推荐答案

有至少两种方法可以做到这一点。

There are at least two ways to do it.

首先

static int FunB(..., void *userdata_)  
{  
   int *a = userdata_;  
   /* Here `a[0]` is 3, and `a[1]` is 45 */
   ...  
}  

int main()  
{  
   int b[] = { 3, 45 };  
   funcA(..., FunB, b); /* Note: `b`, not `&b` */
}  

static int FunB(..., void *userdata_)  
{  
   int (*a)[2] = userdata_;  
   /* Here `(*a)[0]` is 3, and `(*a)[1]` is 45 */
   ...  
}  

int main()  
{  
   int b[] = { 3, 45 };  
   funcA(..., FunB, &b); /* Note: `&b`, not `b` */
}  

选你喜欢哪一个。注意,第二变体的情况下,专门定制当阵列大小是固定的,并在(在这种情况下,准确 2 )编译时已知的。在这种情况下第二个变种实际上是preferable。

Chose which one you like more. Note that the second variant is specifically tailored for the situations when the array size is fixed and known at compile time (exactly 2 in this case). In such situations the second variant is actually preferable.

如果数组的大小不再固定必须使用的第一变体。当然,你必须是大小传递给 FunB 弄好了。

If the array size is not fixed then you have to use the first variant. And of course you have to pass that size to FunB somehow.

注重数组是如何传递到 FuncA的行(作为 B 和b ),它是如何在 FunB 访问(无论是作为 A [I] (*一)[我] )。如果你没有做正确的code可能编译,但将无法工作。

Pay attention how the array is passed to funcA (either as b or as &b) and how it is accessed in FunB (either as a[i] or as (*a)[i]) in both variants. If you fail to do it properly the code might compile but won't work.

这篇关于如何传递函数之间的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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