qu4lizz
qu4lizz

Reputation: 349

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. 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?

Upvotes: 0

Views: 161

Answers (2)

0___________
0___________

Reputation: 67476

The syntax is easier if you typedef function itself:

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

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222352

The type of main (in the form you want) is int main(int, char **).

A pointer to that is int (*main)(int, char **).

An array of those is int (*main[])(int, char **).

A typedef of that is 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.

Upvotes: 2

Related Questions