[英]How to user define array of function pointers which have same prototype as main function?
I have an assignment to typedef function pointers which can point to main function.我有一个可以指向 main 函数的 typedef 函数指针的赋值。 I tried something like this but I'm not sure if it's viable.
我尝试过这样的事情,但我不确定它是否可行。
typedef mainPtr(*f[])(int, char**);
The thing that bothers me is that array size is not defined.困扰我的是未定义数组大小。 How would you do this?
你会怎么做?
The type of main
(in the form you want) is int main(int, char **)
. main
的类型(以您想要的形式)是int main(int, char **)
。
A pointer to that is int (*main)(int, char **)
.指向它的指针是
int (*main)(int, char **)
。
An array of those is int (*main[])(int, char **)
.其中的一个数组是
int (*main[])(int, char **)
。
A typedef of that is typedef int (*mainPtr[])(int, char **);
一个 typedef 是
typedef int (*mainPtr[])(int, char **);
. .
Whether you need a size for the array depends on how you will use the type.您是否需要数组的大小取决于您将如何使用该类型。 If you define and initialize an object of this type, its array size will be completed by counting the initializers.
如果你定义并初始化了一个这种类型的对象,它的数组大小将通过计算初始化器来完成。 For example:
例如:
mainPtr p = { main, NULL };
will create an array with two elements.将创建一个包含两个元素的数组。
In other uses, such as declaring a function parameter with this type, you may not need the array to be complete.在其他用途中,例如声明具有此类型的函数参数,您可能不需要数组是完整的。 An array function parameter is automatically adjusted to be a pointer, so the size is discarded anyway.
数组函数参数会自动调整为指针,因此无论如何都会丢弃大小。 However, if you wish, you could include the size in the
typedef
.但是,如果您愿意,可以在
typedef
包含大小。
The syntax is easier if you typedef function itself:如果您 typedef 函数本身,则语法更简单:
typedef int mainfunc(int, char **);
Then you can use the "normal" pointer syntax:然后你可以使用“普通”指针语法:
/* definition of the function pointer*/
mainfunc *mainptr;
/* definitions of the function pointer arrays*/
mainfunc *mainptrarray[5];
mainfunc *mainptrarray1[] = {foo, bar, NULL};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.