【问题标题】:How can I use a callback to pass an integer to a pointer in C?如何使用回调将整数传递给 C 中的指针?
【发布时间】:2022-01-03 22:00:15
【问题描述】:

我有一个打印“Hello”和一个整数的函数。
我想使用一个回调函数,将整数传递给第一个函数A

//FUnction Pointers in C/C++
#include<stdio.h>
void A(int ree)
{
    printf("Hello %s", ree);
}
void B(void (*ptr)()) // function pointer as argument
{
    ptr();
}
int main()
{
    void (*p)(int) = A(int);
    B(p(3));
}

期望的结果是“Hello 3”。这不会编译。

【问题讨论】:

  • 你有正确的函数指针签名。将 that 定义为B 函数的参数:void B(void(*p)(int))...
  • 第一件事是让代码在没有回调的情况下工作。阅读编译器错误消息(例如 %s 转换和 int 参数之间的不匹配,A(int) 似乎并没有加起来,并且 p(3) 是一个 void 表达式,其中需要非 void 的东西)会有所帮助.然后尝试将您的帖子减少为一个特定问题...
  • p(3) 是一个函数 call,计算调用的结果。如果只传递一个函数指针,它就是p。或者干脆A。简单地说A,这就是你初始化p的东西。 A(int) 在这种情况下没有意义。

标签: c pointers callback


【解决方案1】:
#include<stdio.h>
void A(int ree)
{
    printf("Hello %d", ree); // format specifier for int is %d
}
void B(void (*ptr)(int), int number) // function pointer and the number as argument
{
    ptr(number); //call function pointer with number
}
int main()
{
    void (*p)(int) = A; // A is the identifer for the function, not A(int)
    B(p, 3); // call B with the function pointer and the number
    // B(A, 3); directly would also be possible, no need for the variable p
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2012-11-08
    • 1970-01-01
    相关资源
    最近更新 更多