Home Ask Login Register

Developers Planet

Your answer is one click away!

Iffat Fatima February 2016

Error on dynamically allocating memory to function pointer array

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);


LPs February 2016

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?

jblixr February 2016

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 any all other functions (not restricted to main only). Since the pointer is global it is available globally after initialization at any of the functions.

Post Status

Asked in February 2016
Viewed 3,157 times
Voted 7
Answered 2 times


Leave an answer

Quote of the day: live life