简体   繁体   English

c-将内存分配给指向函数的指针数组

[英]c - allocate memory to an array of pointers to functions

I want my function to create an array and allocate memory for n pointers to functions (for example, functions that have no parameters and return int) and to return a pointer to that array. 我希望我的函数创建一个数组并为n指向函数的指针分配内存(例如,没有参数并返回int的函数),并返回指向该数组的指针。

I tried doing: 我试着做:

void* f(int n){
   return calloc(int (*arrayName[])(void),n);
}

But i'm getting a syntax error. 但是我收到语法错误。 I'm pretty new to c and i tried to dig for an hour how to solve this issue with no success. 我是c新手,我试图挖掘一个小时来解决这个问题,但没有成功。 using the man page i figured calloc is the way to go but i might be wrong. 使用man我认为calloc是解决之道,但我可能错了。

Make your life easier and use typedef s: 使您的生活更轻松,并使用typedef

typedef int (*fp)();

fp * f(size_t n)
{
    return calloc(n, sizeof(fp));
}

The hand-rolled declaration: int (*f(size_t n))() 手动声明: int (*f(size_t n))()

或者,如果您不想使用typedef(提示:出于完整性考虑,您仍然想要typedef ):将类型包装在sizeof()

return calloc(n, sizeof(int (*)(void)));

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

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