如何使用回调将整数传递给C中的指针



我有一个函数可以打印"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));
}

期望的结果是"你好3"。这不会编译。

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

最新更新