bas*_*142 2 c arguments function-pointers
我一直在尝试将函数指针数组传递给函数.一旦进入该函数,我需要一个指向该函数指针数组的指针,但我一直收到错误.当它不是函数参数时,我能够做到这一点.
void (*(*PointerToFuncPtrArray)[2])(unsigned char data[], unsigned char length);
void (*FuncPtr[2])(unsigned char data[], unsigned char length) = {
func1,
func2,
}
void NotArguement(void) // attempt to point to without passing as parameter
{
PointerToFuncPtrArray = &FuncP; // this works
}
// attempt to pass as argument
void AsArguement((void (*ptr[])(unsigned char data[], unsigned char length))
{
PointerToFuncPtrArray = &ptr; // This throws error
}
Run Code Online (Sandbox Code Playgroud)
这引发了......
Error 1 error C2440: '=' : cannot convert from 'void (__cdecl **[])(unsigned char [],unsigned char)' to 'void (__cdecl *(*)[2])(unsigned char [],unsigned char)'
Run Code Online (Sandbox Code Playgroud)
函数参数列表中的数组声明衰减到指针声明.因此,您的函数参数未声明为数组(尽管具有误导性的外观).它被声明为指向指针的指针,这意味着在函数内部,数组类型会不可逆转地丢失.
在这个简单的例子中将报告相同的错误
int x[2];
...
void foo(int a[2]) /* <- equivalent to `void foo(int *a)` */
{
int (*p1)[2] = &x; /* <- OK */
int (*p2)[2] = &a; /* <- ERROR: can't convert `int **` to `int (*)[2]` */
}
...
foo(x);
Run Code Online (Sandbox Code Playgroud)
在上面的例子a中不再是一个数组.它是一个int *类型的指针,意味着它&a具有类型int **,不能用于初始化类型的对象int (*)[2].
在C中,将数组传递给函数同时保留参数的"数组"的唯一方法是将其"通过指针传递给整个数组",如
int x[2];
...
void foo(int (*a)[2])
{
int (*p)[2] = a; /* <- OK */
}
...
foo(&x);
Run Code Online (Sandbox Code Playgroud)
请注意,&操作符的应用程序从函数内部"移动"到调用点.
代码中的相同修改如下所示
void AsArguement(void (*(*ptr)[2])(unsigned char data[], unsigned char length))
{
PointerToFuncPtrArray = ptr;
}
Run Code Online (Sandbox Code Playgroud)
您只需记住&在调用此函数时将运算符应用于数组参数.