简体   繁体   中英

How can I pass arguments to the function pointer in following code?

I tried those code but there is some issue with scope of parameters a and b. please someone help me out here.

#include<conio.h>
#include<stdio.h>
int add(int x, int y) {
    return (x + y);
}
void passptr(int( * fp)(int a, int b)) {
    int result = ( * fp)(a, b);
    printf("%d", result);
}
int main() {
    add(3, 5);
    passptr( & add);
    getch();
    return 0;
}

This kind of call is easier to understand if you typedef your function pointer:

#include<conio.h>
#include<stdio.h>

// addFuncPtr_t is a pointer to a function that:
// - returns int
// - takes two int arguments
typedef int ( *addFuncPtr_t )( int, int );

int add(int x, int y) {
    return (x + y);
}
void passptr(addFuncPtr_t fp, int a, int b) {
    int result = fp(a, b);
    printf("%d", result);
}
int main() {
    add(3, 5);

    // note that the function is passed separately from
    // the arguments - add(3,5) would *call* the function
    // instead of passing the address of the function
    passptr( add, 3, 5 );
    getch();
    return 0;
}
void passptr(int (*fp)(int a,int b))
{
    int result=(*fp)(a,b);
    printf("%d",result);
}

a and b here are just descriptive names you have given to the parameters of the function pointer, they aren't declared variables. Just call the function with valid arguments:

//call with literals
int result = (*fp)(1,2);

//or variables
int a = 1;
int b = 2;
int result = (*fp)(a,b);

//or pass as arguments
void passptr(int (*fp)(int,int), int a, int b) {
    int result = (*fp)(a,b)
}

//and call like this
passptr(&add, 1, 2);

You want this:

void passptr(int (*fp)(int, int), int a, int b)  // corrected argument list
{
 int result=(*fp)(a,b);
 printf("%d",result);
}
int  main()
{
 add(3,5);              // this is useless leftover from your original code
 passptr(&add, 3, 5);   // added parameters 3 and 5 here
 getch();
 return 0;
}

In your void passptr(int( * fp)(int a, int b)) a and b are not parameters to the passptr function but just placeholders.

You may want to try this:

#include<conio.h>
#include<stdio.h>
int add(int x, int y) {
    return (x + y);
}
void passptr(int( * fp)(int a, int b)) {
    int result = ( * fp)(3, 5);
    printf("%d", result);
}
int main() {
    add(3, 5);
    passptr( & add);
    getch();
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM