0

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?

4
  • 1
    typedef int (*mainPtr)(int,char**); Commented Jun 19, 2021 at 10:57
  • No it is not. You have two identifiers here mainPtr and f. Which one are you trying to typedef? Commented Jun 19, 2021 at 11:01
  • Please show how you intend to use this afterwards. Commented Jun 19, 2021 at 11:08
  • @PSKocik yeah, that's one pointer but what about array of those? Commented Jun 19, 2021 at 11:37

2 Answers 2

2

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.

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

Comments

0

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

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.