开发者

how to pass arrays between functions

Can someone help me? I having a problem with a C progra开发者_如何学Pythonm. Here it is:

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)  
}  

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.

Thanks


There are at least two ways to do it.

First

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` */
}  

Second

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` */
}  

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.

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜