I am trying to use a function pointer to call another function, but it gives me an error this error:
Argument of type "void" is incompatible with parameter of type "void (*)(int a)
Here's my code:
#include<stdio.h>
#include<stdlib.h>
void print(void (*ptr)(int));
void printint(int);
int main()
{
char a;
int b;
scanf("%c %d",&a,&b);
print(printint(b));
return 0;
}
void print(void (*ptr)(int a))
{
ptr(a);
}
void printint(int a)
{
// printf("executed");
printf("%d",a);
}
I think I wrongly used the function pointer.
Can someone explain how to implement this program in the correct way?
The problem is that print(printint(b));
is calling printint(b)
first and then passing its return value (which is void
) to print()
. Hence the error.
You need to pass the b
value to print()
in a separate parameter, and then it can pass the value to printint()
, eg:
#include <stdio.h>
#include <stdlib.h>
typedef void (*funcptr)(int);
void print(funcptr, int);
void printint(int);
int main()
{
char a;
int b;
scanf("%c %d", &a, &b);
print(printint, b);
return 0;
}
void print(funcptr ptr, int a)
{
ptr(a);
}
void printint(int a)
{
// printf("executed");
printf("%d", a);
}