[英]In C, modify the target of a pointer to an array of pointers when passed as argument to a function
[英]Unable to “point to” passed array of function pointers in C
我一直在嘗試將函數指針數組傳遞給一個函數。 進入該函數后,我需要一個指向該函數指針數組的指針,但我不斷遇到錯誤。 當它不是函數參數時,我能夠做到。
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
}
拋出...
Error 1 error C2440: '=' : cannot convert from 'void (__cdecl **[])(unsigned char [],unsigned char)' to 'void (__cdecl *(*)[2])(unsigned char [],unsigned char)'
函數參數列表中的數組聲明衰減為指針聲明。 因此,您的函數參數未聲明為數組(盡管具有誤導性的外觀)。 它被聲明為指針到指針,這意味着在函數內部數組類型不可逆地丟失。
在這個簡單的示例中將報告相同的錯誤
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);
在上面的示例中, a
不再是數組。 它是int *
類型的指針,意味着&a
具有int **
類型,不能用於初始化int (*)[2]
類型的對象。
在C語言中,在保留參數“數組性”的同時將數組傳遞給函數的唯一方法是“通過指向整個數組的指針”傳遞它,如
int x[2];
...
void foo(int (*a)[2])
{
int (*p)[2] = a; /* <- OK */
}
...
foo(&x);
注意, &
運算符的應用程序從函數內部“移動”到了調用點。
您代碼中的相同修改如下所示
void AsArguement(void (*(*ptr)[2])(unsigned char data[], unsigned char length))
{
PointerToFuncPtrArray = ptr;
}
您只需要記住在調用此函數時對數組參數應用&
運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.