2

I have a problem with the code that uses function pointers, take a look:

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

And it produces errors:

/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 ===|

I used a Code::Blocks to compile it.

Its simple, when I dont have any arguments but with some, I got confused:

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

2 Answers 2

8

Your function pointer does not fit to your function declarations. Try defining it as

typedef void (*VFUNCV)(int, double);
Sign up to request clarification or add additional context in comments.

Comments

6

Fix typedef to

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

as fun1 and fun2 accepts two argument of type int and double

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.