Array of function pointer in C

I want to create an array of function pointers and be able to call them in a for loop. How can i achieve this? I tried:

void (**a) (int);
a[0] = &my_func1;
a[1] = &my_func2;
a[2] = &my_func3;

for ( i = 0; i < 3; i++){
    a[0]();
    (*a[0])(); // Neither does work
}

But I skip some syntax, I think:

error: too few arguments to function ‘*(a + (long unsigned int)((long unsigned int)i * 8ul))’
+3
source share
7 answers

I assume the code below is what you need.

typedef void * func_pointer(int);

func_pointer fparr[10];

for(int i = 0; i<10; i++)
{
     fparr[i](arg); //pass the integer argument here
}
+2
source

The function you declare is expected to take an int value as a parameter:

a[0](1);

Also note that you are declaring a pointer to a pointer for functions, but you are not allocating any memory to them (I assume this is only an example). Otherwise, it should be:

void (*a[3]) (int);
+7
source

, a ( ) , int - int, , a[0](42);.

+3

1) ?

2) , (* a [0])();,

+1

typedef void (*pfun)(int);, pfun a[3]; - , .

:

typedef void (*pfun)(int);

int main() {
    pfun a[3];
    a[0] = myfunc1;    // or &myfunc1 whatever you like
    a[1] = myfunc2;
    a[2] = myfunc3;
}
+1

.

void (**a) (int); // here it takes an int argument
a[0] = &my_func1;
a[1] = &my_func2;
a[2] = &my_func3;

for ( i = 0; i < 3; i++){
    a[0](); // here you do not give an argument
}

, a, .

void my_func1(int i) {
    ;
}
void my_func2(int i) {
    ;
}
void my_func3(int i) {
    ;
}

int main() {
    void (**a) (int);
    a = malloc(3*sizeof(void*)); // allocate array !
    a[0] = &my_func1;
    a[1] = &my_func2;
    a[2] = &my_func3;

    for (int i = 0; i < 3; i++){
        a[i](1); // respect your own function signature
    }
    free(a); // it always a good habit to free the memory you take
    return 0;
}
+1

:

void my_func1(int x){}
void my_func2(int x){}
void my_func3(int x){}

void (*a[])(int)={my_func1,my_func2,my_func3};


int i;
for(i=0;i<sizeof a/sizeof*a;++i)
  a[i](i);

- '&' .

+1

All Articles