R
R
Refiru2020-08-23 15:32:28
C++ / C#
Refiru, 2020-08-23 15:32:28

How to create a two-dimensional array of pointers to C functions?

Hello. I'm just learning C, but I want to solve problems now.
In searching the Internet, I found a piece of C code that I adapted to my structure.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
void (*pn[2])(void);

void f1(){
    printf("Test\n");
}
    

void f2(){
    printf("Тест 2\n");

}
    
int test(){
    pn[0]=&f1;
    pn[1]=&f2;
    return 0;
}
int main() {
    setlocale(LC_ALL, "ru_RU.utf8"); 
    test();
    pn[0](); 
    pn[1]();
    return 0;
}

For some reason, there are no options when inserting the code, C! C++ only, unfair.

The bottom line is that in a separate file I have a lot of functions 50+ and I will add them.
They will be called by a loop on the array parameter. I know the number of functions, the statistical array is enough for me.

But I need exactly a vector array where x and y will be?

Something like array[1][2] since I'm just learning this language. There are questions.

Even this code is not easy for me to understand, so if someone can explain in an accessible way.
I will be grateful.
It is also not very convenient to assign a value manually each time, although I put up with that.
I would appreciate any advice and tips!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Demin, 2020-08-23
@Refiru

An array of functions can also be initialized without an ampersand:

int test() {
    pn[0]=f1;
    pn[1]=f2;
    return 0;
}

This is how you can create a two-dimensional array of functions:
#include <stdio.h>

void p1() { puts("p1"); }
void p2() { puts("p2"); }
void p3() { puts("p3"); }
void p4() { puts("p4"); }

int main() {
  void (*pn[2][2])() = {
    {p1, p2},
    {p3, p4},
  };
  
  for(int i = 0; i < 2; i++)
      for(int j = 0; j < 2; j++)
          pn[i][j]();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question