aTe*_*ile 2 c function-pointers function
我想知道与双指针不同(int**),我们可以有双函数指针吗?
我的意思是函数指针指向另一个函数指针的地址?
\n我想要类似的东西
\nint add(int A , int B){\n return A+B;\n}\n\nint main(void){\n\n int (*funcpointerToAdd)(int,int) = add; // single function pointer pointing to the function add\n printf("%d \\n",funcpointerToAdd(2,3));\n \n\n int (**doubleFuncPointerToAdd)(int,int) = &funcpointerToAdd;\n printf("%d \\n",doubleFuncPointerToAdd(2,3));\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n但这给了我一个错误called object \xe2\x80\x98doubleFuncPointerToAdd\xe2\x80\x99 is not a function or function pointer
无论如何这有可能做这件事吗?
\n小智 5
您可以使用指向函数指针的指针,但必须首先引用它们一次:
int add(int A , int B){
return A+B;
}
int main(void){
int (*funcpointerToAdd)(int,int) = &add;
//By the way, it is a POINTER to a function, so you need to add the ampersand
//to get its location in memory. In c++ it is implied for functions, but
//you should still use it.
printf("%d \n",funcpointerToAdd(2,3));
int (**doubleFuncPointerToAdd)(int,int) = &funcpointerToAdd;
printf("%d \n",(*doubleFuncPointerToAdd)(2,3));
//You need to dereference the double pointer,
//to turn it into a normal pointer, which you can then call
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于其他类型也是如此:
struct whatever {
int a;
};
int main() {
whatever s;
s.a = 15;
printf("%d\n",s.a);
whatever* p1 = &s;
printf("%d\n",p1->a); //OK
//x->y is just a shortcut for (*x).y
whatever** p2 = &p1;
printf("%d\n",p2->a); //ERROR, trying to get value (*p2).a,
//which is a double pointer, so it's equivalent to p1.a
printf("%d\n",(*p2)->a); //OK
}
Run Code Online (Sandbox Code Playgroud)