C 语言中可以有双函数指针吗?

标签 c function function-pointers

我想知道与双指针 (int**) 不同,我们可以有双函数指针吗?

我的意思是函数指针指向另一个函数指针的地址?

我想要类似的东西

int add(int A , int B){
    return A+B;
}

int main(void){

    int (*funcpointerToAdd)(int,int) = add; // single function pointer pointing to the function add
    printf("%d \n",funcpointerToAdd(2,3));
  

    int (**doubleFuncPointerToAdd)(int,int) = &funcpointerToAdd;
    printf("%d \n",doubleFuncPointerToAdd(2,3));

    return 0;
}

但这给了我一个错误称为对象“doubleFuncPointerToAdd”不是函数或函数指针

无论如何都可以做这件事吗?

最佳答案

您可以使用指向函数指针的指针,但必须先引用它们一次:

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

对于其他类型也是如此:

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
}

关于C 语言中可以有双函数指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72198689/

相关文章:

c - 尝试学习 malloc 的问题

javascript - 回调函数没有执行

c - 如何为小端编码奇数长度字节地址?

c - 为什么这个简单的 Linux C 程序在运行时加载 .so 会崩溃?

c++ - 有限状态机中的函数指针

c++ - 与 Java 无关的 list 文件是什么?

c - 如何在普通 C 中继承结构

c - 从数组中随机选择两个元素并交换C中的值

c++ - 在 vector C++ 的矩阵中查找条目

python - 从全局环境中的函数内部使用 exec 定义函数