关于C / C ++中函数指针的问题

时间:2013-03-22 05:43:05

标签: c++ c function-pointers

我最近正在阅读Linux内核。 我发现在很多情况下他们使用结构“typedef xxx f(xxx)”,但我无法理解它是如何工作的。 (像函数指针一样?)

这是我的测试代码。

#include<stdio.h>
typedef int Myfunc(int);
typedef int (*point_to_myfunc)(int);
static Myfunc example;
static int example(int a){
    printf("example a=%d\n", a);
    return 1;
}
static void example2(Myfunc* f){
    printf("example2\n");
    f(2);
}
static void example3(int (*)(int));
static void example3(int (*point_to_Myfunc)(int)){
    printf("example3\n");
    point_to_Myfunc(3);
}
int main(){
    point_to_myfunc f=&example;
    example2(f);
    example3(f);
    return 0;
}

有人可以为我提供简短的解释吗? THX〜

4 个答案:

答案 0 :(得分:3)

#include <stdio.h>
typedef int Myfunc(int);

Myfunc是类型的名称;它是一个带有int参数并返回int的函数。

typedef int (*point_to_myfunc)(int);

point_to_myfunc是一个指向函数的指针,该函数采用int参数并返回int。如果你愿意的话,你也可以:typedef Myfunc *ptr_to_myfunc;(同一类型的另一个名字)。

static Myfunc example;

这表示'存在一个名为example Myfunc的函数。

static int example(int a)
{
    printf("example a=%d\n", a);
    return 1;
}

这是example的可能实现。您不能在类型函数的定义中使用typedef名称来表示Myfunc

static void example2(Myfunc *f)
{
    printf("example2\n");
    f(2);
}

这是一个指向Myfunc的函数。行f(2);使用参数2调用指向的函数,并忽略返回的值。

static void example3(int (*)(int));

这将example3声明为一个函数,该函数获取一个带有int参数并返回int结果的函数的指针。它可以写成static void example3(point_to_myfunc);static void example3(ptr_to_myfunc);static void example3(Myfunc *);

static void example3(int (*point_to_Myfunc)(int))
{
    printf("example3\n");
    point_to_Myfunc(3);
}

这是example3的实现。

int main(void)
{
    point_to_myfunc f = &example;
    example2(f);
    example3(f);
    return 0;
}

这个程序有一个变量f,它是一个指向函数的指针。有趣的是,你可以:

    point_to_myfunc f2 = example;
    point_to_myfunc f3 = *example;

等。他们都意味着同样的事情。

您也可以使用以下方式调用它们:

    (*f2)(101);
    (**f3)(103);

初始化的标准表示法既不使用&也不使用*。如果您是一名旧学校C程序员,您可以使用(*f2)(101)表示法调用函数指针;在C89标准之前,这是调用函数指针的唯一方法。现代风格往往是f2(101);

答案 1 :(得分:1)

typedef int Myfunc(int);

这意味着Myfunc是一个函数的类型,它接受一个int参数并返回一个int。

这一行:

static Myfunc example;

与说

相同
static int example(int);

向前声明示例函数。

这样做的一个用途是更清楚地表明特定功能集用于特定目的。

typedef char CharacterConverter(char);

extern CharacterConverter make_upper_case;
extern CharacterConverter make_lower_case;

extern void process_string(char *s,CharacterConverter *f);
    // easier to see that make_upper_case and make_lower_case are valid arguments.

答案 2 :(得分:1)

Vaughn Cato是对的, 另外,

typedef int (*point_to_myfunc)(int);

定义了一个函数指针,它意味着point_to_myfunc是一个类型,我们可以像这样使用它:

point_to_myfunc f=&example;

现在f就像example(),我们可以用f()调用方法示例

答案 3 :(得分:0)

typedef在定义类型时很有用。

例如: char *a, b;定义了一个指针“a”和一个char b。 char *a, *b定义了两个char指针。 如果使用typedef,则会很清楚:

typedef char* PCHAR;
PCHAR a,b;

现在,a和b都是char指针。

typedef int Myfunc(int);
typedef int (*point_to_myfunc)(int);

这两行定义了一对,一种函数格式和一种可以指向函数的指针类型,因此在使用它们时会更清晰,更明显。