C言語の関数ポインタはどのように機能しますか? 質問する

C言語の関数ポインタはどのように機能しますか? 質問する

最近、C の関数ポインターについて少し経験しました。

そこで、皆さんの質問に自ら答えるという伝統を引き継ぎ、このテーマについて簡単に知りたい人のために、ごく基本的な内容を簡単にまとめることにしました。

ベストアンサー1

C言語の関数ポインタ

まず、私たちが指し示す基本的な関数から始めましょう:

int addInt(int n, int m) {
    return n+m;
}

intまず最初に、 2 を受け取って を返す関数へのポインターを定義しましょうint

int (*functionPtr)(int,int);

これで、関数を安全に指定できるようになりました。

functionPtr = &addInt;

関数へのポインターができたので、それを使用しましょう。

int sum = (*functionPtr)(2, 3); // sum == 5

ポインタを別の関数に渡すことも基本的に同じです。

int add2to3(int (*functionPtr)(int, int)) {
    return (*functionPtr)(2, 3);
}

戻り値にも関数ポインターを使用できます (面倒なので、頑張ってください)。

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

しかし、 を使用する方がはるかに便利ですtypedef

typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
    printf("Got parameter %d", n);
    myFuncDef functionPtr = &addInt;
    return functionPtr;
}

おすすめ記事