Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
Incompatible pointer types warning when printing function pointers

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!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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]() );
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda