Home > database >  Incompatible pointer types warning when printing function pointers
Incompatible pointer types warning when printing function pointers

Time:04-12

I am trying to create an array of function pointers, so that I can print out output from the functions by using the pointers. (For an exercise from the Effective C book.)

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

int a(void) { return 1; }
int b(void) { return 2; }
int c(void) { return 3; }

int main(void)
{

    int(*func_arr)[3] = {&a, &b, &c};
    printf("%d\n", (*func_arr)[0]);
}

However, when I compile it, I get the warnings

starting.c:10:26: warning: incompatible pointer types initializing 'int (*)[3]' with an expression of type
      'int (*)(void)' [-Wincompatible-pointer-types]
    int(*func_arr)[3] = {&a, &b, &c};
                         ^~
starting.c:10:30: warning: excess elements in scalar initializer
    int(*func_arr)[3] = {&a, &b, &c};
                             ^~

And, when I run the program, I get an output of -443987883, while it should just be 1.

Does anyone know the solution for this? Thank you!

CodePudding user response:

This declaration

int(*func_arr)[3] = {&a, &b, &c};

declares a pointer to the array type int[3].

So there is declared a scalar object of a pointer type that you are trying to initialize using a brace enclosed list of initializers with more than one initializer of an incompatible pointer type.

Instead you need to write

int ( *func_arr[3] )( void ) = { a, b, c };

The function designators used as initializers are implicitly converted to pointers to the functions. So there is no need to write as for example &a though such an expression is also valid to be used as an initializer.

To simplify the array declaration you could introduce a typeded name for the function pointer type.

For example

typedef int ( *FnPtr )( void );

Now the array declaration can look the following way

FnPtr func_arr[3] = { a, b, c };

And to output results of function calls you need to write calls of printf like

printf("%d\n", func_arr[0]() );
  • Related