简体   繁体   English

为函数指针数组动态分配内存时出错

[英]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 我在编译时收到以下错误, 错误C2099:初始化器在下一行不是常量

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

You cannot init with malloc a global variable. 您不能使用malloc初始化全局变量。

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? 还要看看: 我是否强制执行malloc return?

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. 由于malloc()也是一个函数调用,因此无法执行。

So you can declare the global pointer variable and initialize it in any of your functions (not restricted to main only). 因此,您可以声明全局指针变量并在任何函数中对其进行初始化(不仅限于main )。 Since the pointer is global it is available globally after initialization to any of your functions. 由于指针是全局的,因此在初始化任何函数后全局可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM