0
int kpSize = 4;
int kpIdx = 0;

typedef int (*EventHandler) (void *);

EventHandler *keyFuncArray = (EventHandler *) malloc(sizeof(EventHandler) * kpSize);

I get the following error on compiling, error C2099: initializer is not a constant on the following line

EventHandler *keyFuncArray = (EventHandler *) malloc(sizeof(EventHandler) * kpSize);
Iffat Fatima
  • 1,610
  • 2
  • 16
  • 27
  • 4
    Is your code like you posted? I mean is the keyFuncArray init outside function, as a global variable? If yes, it is wrong... – LPs Feb 08 '16 at 11:07
  • This kind of initialization isn't allowed in C. Works in C++. – Frankie_C Feb 08 '16 at 11:09
  • 1
    **error C2099: initializer is not a constant** means that the initialization value of a global variable must be constant. – barak manos Feb 08 '16 at 11:12
  • 1
    Why dynamically allocate a global array of 4 pointers? – n. m. could be an AI Feb 08 '16 at 11:20
  • It would be better not to hide the pointer behind a `typedef`. If you did `typedef int EventHandler (void*);` then you could increase type safety drastically and get rid of the obscure pointer-to-function-pointer: `EventHandler* keyFuncArray = malloc(sizeof(EventHandler*[kpSize]));`. I can't come up with a case where a pointer to a function pointer would make sense. – Lundin Feb 08 '16 at 12:31

2 Answers2

3

You cannot init with malloc a global variable.

You must write, eg:

EventHandler *keyFuncArray;

int main ()
{
    keyFuncArray = malloc(sizeof(EventHandler) * kpSize)

   // STUFF:..

   return 0;
}

Take a look also to: Do I cast malloc return?

Community
  • 1
  • 1
LPs
  • 16,045
  • 8
  • 30
  • 61
2

You can only do declarations in the global scope. So a function call can't execute in the global scope. As malloc() is also a function call, it couldn't execute.

So you can declare the global pointer variable and initialize it in any of your functions (not restricted to main only). Since the pointer is global it is available globally after initialization to any of your functions.

jblixr
  • 1,345
  • 13
  • 34