2

関数ポインターを使用するコードに問題があります。以下をご覧ください。

#include <stdio.h>
#include <stdlib.h>

typedef void (*VFUNCV)(void);

void fun1(int a, double b) { printf("%d %f fun1\n", a, b); }
void fun2(int a, double b) { printf("%d %f fun2\n", a, b); }

void call(int which, VFUNCV* fun, int a, double b)
{
    fun[which](a, b);
}

int main()
{
    VFUNCV fun[2] = {fun1, fun2};
    call(0, fun, 3, 4.5);
    return 0;
}

そして、それはエラーを生成します:

/home/ivy/Desktop/CTests//funargs.c||In function ‘call’:|
/home/ivy/Desktop/CTests//funargs.c|11|error: too many arguments to function ‘*(fun + (unsigned int)((unsigned int)which * 4u))’|
/home/ivy/Desktop/CTests//funargs.c||In function ‘main’:|
/home/ivy/Desktop/CTests//funargs.c|16|warning: initialization from incompatible pointer type [enabled by default]|
/home/ivy/Desktop/CTests//funargs.c|16|warning: (near initialization for ‘fun[0]’) [enabled by default]|
/home/ivy/Desktop/CTests//funargs.c|16|warning: initialization from incompatible pointer type [enabled by default]|
/home/ivy/Desktop/CTests//funargs.c|16|warning: (near initialization for ‘fun[1]’) [enabled by default]|
||=== Build finished: 1 errors, 4 warnings ===|

Code::Blocks を使用してコンパイルしました。

引数がない場合は簡単ですが、いくつかあると混乱しました:

#include <stdio.h>
#include <stdlib.h>

typedef void (*VFUNCV)(void);

void fun1() { printf("fun1\n"); }
void fun2() { printf("fun2\n"); }

void call(int which, VFUNCV* fun)
{
    fun[which]();
}

int main()
{
    VFUNCV fun[2] = {fun1, fun2};
    call(1, fun);
    return 0;
}
4

2 に答える 2

8

関数ポインタが関数宣言に適合しません。と定義してみてください。

typedef void (*VFUNCV)(int, double);
于 2013-08-07T11:32:43.350 に答える
6

修正typedefする

typedef void (*VFUNCV)(int , double );

as型と型の 2 つの引数fun1fun2受け入れますintdouble

于 2013-08-07T11:31:53.570 に答える