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);
5
  • 4
    Is your code like you posted? I mean is the keyFuncArray init outside function, as a global variable? If yes, it is wrong... Commented Feb 8, 2016 at 11:07
  • This kind of initialization isn't allowed in C. Works in C++. Commented Feb 8, 2016 at 11:09
  • 1
    error C2099: initializer is not a constant means that the initialization value of a global variable must be constant. Commented Feb 8, 2016 at 11:12
  • 1
    Why dynamically allocate a global array of 4 pointers? Commented Feb 8, 2016 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. Commented Feb 8, 2016 at 12:31

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.