Search code examples
cpointersfunction-pointersvoid-pointersjump-table

How to reference deeply nested function pointer array in C?


I have essentially this:

void **a;

typedef void (*ExampleFn)();

void
foo() {
  puts("hello");
}

void
init() {
  ExampleFn b[100] = {
    foo
  };

  a = malloc(sizeof(void) * 10000);

  a[0] = b;
}

int
main() {
  init();

  ExampleFn x = a[0][0];
  x();
}

But when running I get all kinds of various errors, such as this:

error: subscript of pointer to function type 'void ()'

How do I get this to work?

Doing something like ((ExampleFn*)a[0])[0](); gives a segmentation fault.


Solution

  • It seems like you're trying to make an array of function pointers. The code could look like this (partial code):

    ExampleFn *a;
    
    void init()
    {
        a = malloc(100 * sizeof *a);
        a[0] = foo;
    }
    
    int main()
    {
        init();
        ExampleFn x = a[0];
        x();
    }
    

    In Standard C, the void * type is only for pointers to object type, not pointers to function.

    You can make a 2-D or 3-D jagged array in the same way as you would for object types (e.g. see here), just use ExampleFn instead of int as in that example.