-2

Suppose I have a pointer to pointer to function taking int and returning int*.

int* (**ptr)(int) //i hope i'm not wrong here

How should I alloc memory for that pointer using new? And how can I create an array of pointers to functions with new? I was trying something like this:

int* (**ptr)(int)  = new int* (*)(int);

but it shows "expected primary-expression before ‘)’ token"

myschu
  • 91
  • 1
  • 8

2 Answers2

0

Here is a demonstrative program that shows how the array can be declared with a typedef and without a typedef.

#include <iostream>

int * func1(int value)
{
    static int x = value;

    return &x;
}

int * func2(int value)
{
    static int x = value;

    return &x;
}

int * func3(int value)
{
    static int x = value;

    return &x;
}

int main()
{
    const int N = 3;

    typedef int * (*PFunc)(int);
    PFunc *ptr = new PFunc[N] { func1, func2, func3 };

    int* (**ptr1)(int) = new ( int* (*[N])(int) ){ func1, func2, func3 };

    for (int i = 0; i < N; i++)
    {
        std::cout << *ptr[i]( i ) << std::endl;
    }

    std::cout << std::endl;

    for (int i = 0; i < N; i++)
    {
        std::cout << *ptr1[i]( i ) << std::endl;
    }

    std::cout << std::endl;

    return 9;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

The correct syntax to create an array of functions pointers is as follows:

int* (**ptr)(int) = new (int*(*[5])(int));

This creates an array of 5 function pointers, where each function pointer is of type int *(*)(int).

This can be simplified with a typedef:

typedef int *(*fp)(int);
fp *ptr2 = new fp[5];
dbush
  • 205,898
  • 23
  • 218
  • 273