Home > Blockchain >  How can I use a callback to pass an integer to a pointer in C?
How can I use a callback to pass an integer to a pointer in C?

Time:11-26

I have a function that prints 'Hello' and an integer.
I would like to use a callback function that passes the integer into the first function 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));
}

Desired result would be 'Hello 3'. This doesn't compile.

CodePudding user response:

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