简体   繁体   中英

warning: initialisation from incompatible pointer type via function table in c

(code examples haven't been tested - just are for example)

I have several declarations like so:

void (* const a[])(void) = {func1, func2};
void func1() {};
void func2() {};
a[0]();

That compiles (if it was real code...) and the should runs func1.

However, if I want to pass arguments such as:

a[0](int 10);

Then I change my declarations:

void (* const a[])(int) = {func1, func2};
void func1(int foo) {};
void func2(int foo) {};
a[0](10);

That also compiles but I get the following warning:

warning: initialisation from incompatible pointer type.

The resulting code also runs fine, but I suspect that the declaration is at fault. I can find several examples on how to build function tables that do not pass parameters but am struggling to find an example that shows how to do it with one.

Most likely the declarations of func1 and func2 declare them as taking void as a parameter, rather than taking int . You probably have

void func1(void);
void func2(void);

in some header file. Instead, you need

void func1(int);
void func2(int);

This is because the declaration

void (*const a[])(int)

means that a is an array of function pointers taking int and returning void .

At the time you initialize a , func1 and func2 aren't declared, so they have the default type declarations of int () . Declare func1 and func2 before initializing a .

void func1(int);
void func2(int);

void (* const a[])(int) = {func1, func2};
void func1(int foo) {};
void func2(int foo) {};
a[0](10);

I believe that having typedef -s for defining signature of functions make the code more readable. So why not:

typedef void signature_t(int);
void foo1(int);
void foo2(int);
const signature_t* funarray[] = { foo1, foo2 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM