0

我基本上有这个:

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

但是在运行时,我会遇到各种错误,例如:

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

我怎样才能让它工作?

做类似的事情((ExampleFn*)a[0])[0]();会导致分段错误。

4

1 回答 1

0

似乎您正在尝试创建一个函数指针数组。代码可能如下所示(部分代码):

ExampleFn *a;

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

int main()
{
    init();
    ExampleFn x = a[0];
    x();
}

在标准 C 中,void *类型仅用于指向对象类型的指针,而不是指向函数的指针。

您可以按照与对象类型相同的方式制作 2-D 或 3-D 锯齿状数组(例如,请参见此处),只需使用ExampleFn而不是int在该示例中。

于 2020-04-12T02:21:16.300 回答