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

199
Visualizações
How to make function pointers in a structure constant to be used to initialise a constant array?

I have the following constant struct which holds function pointers:

/* module1.h */

typedef struct my_struct my_struct_t;

struct my_struct
{
   void (*funcPtr1)(void);
   void (*funcPtr2)(void);
}

extern const my_struct_t myStruct1;



/* module1.c */

#include <module1.h>

static void func1(void)
{
   // do something
}

static void func2(void)
{
   // do something else
}

const my_struct_t myStruct1 = {
   .funcPtr1 = &func1,
   .funcPtr2 = &func2
}

So far so good!

Now I want to create a constant array of the above struct and assign the function pointers from instances of the struct:

/* module2.c */

#include <module1.h>

const my_struct_t arrayOfMyStruct[] = {
   { myStruct1.funcPtr1, myStruct1.funcPtr2 },
   // ...
}

Compiler throws an error and says, that the expressions "myStruct1.funcPtr1" and "myStruct1.funcPtr2" were not constant.
What is wrong?

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

0

myStruct1 is declared with the qualifier const, but it isn't constant. Static initialization requires it to be, and arrayOfMyStruct has static storage duration.

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

You can initialize it by using the functions directly: { func1, func2 },

or take the address of the pointer: { &myStruct1.funcPtr1, &myStruct1.funcPtr2 },

in which case you will have to use a different struct type for the array:

typedef struct 
{
   void (*const *funcPtr1)(void);
   void (*const *funcPtr2)(void);
} my_struct2_t;

And syntax for calling the function has to be changed:

(*arrayOfMyStruct[0].funcPtr2)();
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