如何在以下代码中将参数传递给函数指针?

时间:2016-01-11 10:29:34

标签: c function-pointers

我尝试了这些代码,但参数a和b的范围存在一些问题。请有人帮帮我。

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

4 个答案:

答案 0 :(得分:7)

如果你typedef你的函数指针,这种调用更容易理解:

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

答案 1 :(得分:2)

void passptr(int (*fp)(int a,int b))
{
    int result=(*fp)(a,b);
    printf("%d",result);
}

ab这里只是你给函数指针参数的描述性名称,它们不是声明的变量。只需使用有效参数调用该函数:

//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);

答案 2 :(得分:2)

你想要这个:

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

您的void passptr(int( * fp)(int a, int b)) ab不是passptr功能的参数,只是占位符。

答案 3 :(得分:1)

你可能想试试这个:

#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;
}
相关问题