如何在函数之间传递数组

有人能帮我吗? 我遇到了C程序的问题。 这里是:

在我的主要部分,我调用一个函数(func A),其中两个参数是第二个函数(fun B)和“user data”(原则上可以是单个数字,char或数组)。 这个“用户数据”也是函数B的一个参数。当“用户数据”是一个整数但是现在我需要将它用作数组时,我已经完成了所有工作。 所以目前的工作结构是这样的:

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

所以现在我希望b在main中作为一个数组(例如{3,45}),以便将更多的单个“数据”传递给函数B.

谢谢

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

第一

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

选择你更喜欢哪一个。 请注意,第二个变体是专门针对arrays大小固定并在编译时已知的情况(在这种情况下恰好为2 )而定制的。 在这种情况下,第二种变体实际上是优选的。

如果数组大小未修复,则必须使用第一个变体。 当然,你必须以某种方式将这个大小传递给FunB

注意如何将数组传递给funcAb&b )以及如何在FunB访问它(如a[i](*a)[i] )两种变体。 如果你没有正确地执行它,代码可能会编译但不起作用。