C言語では、関数のポインタ変数を宣言し、関数を変数に代入しその変数を関数として使用することができます。
本記事では、関数のポインタの2次元配列を作成し、マトリックスとして利用できる方サンプルを記します。
関数のポインタを2次元配列に入れることにより、X,Yにて関数を呼び出すことができます。
状態遷移が複雑なプログラムなど、switch case を多用しなくても、X,Yという二つの状態を管理しておけば、
状態に対応した関数を呼び出すことができます。
マトリックスのC言語サンプルソースを以下に記します。
#include <stdio.h> typedef void (*FUNCP)(void); /* Function Matrix array */ FUNCP funcbox[3][3]; /* Matrix functions */ void func_0_0(void) { printf("func_0_0\n"); } void func_0_1(void) { printf("func_0_1\n"); } void func_0_2(void) { printf("func_0_2\n"); } void func_1_0(void) { printf("func_1_0\n"); } void func_1_1(void) { printf("func_1_1\n"); } void func_1_2(void) { printf("func_1_2\n"); } void func_2_0(void) { printf("func_2_0\n"); } void func_2_1(void) { printf("func_2_1\n"); } void func_2_2(void) { printf("func_2_2\n"); } /* set function pointer array */ void init_func(void) { funcbox[0][0] = &func_0_0; /* x=0, y=0 */ funcbox[0][1] = &func_0_1; /* x=0, y=1 */ funcbox[0][2] = &func_0_2; /* x=0, y=2 */ funcbox[1][0] = &func_1_0; /* x=1, y=0 */ funcbox[1][1] = &func_1_1; /* x=1, y=1 */ funcbox[1][2] = &func_1_2; /* x=1, y=2 */ funcbox[2][0] = &func_2_0; /* x=2, y=0 */ funcbox[2][1] = &func_2_1; /* x=2, y=1 */ funcbox[2][2] = &func_2_2; /* x=2, y=2 */ } int main(void) { int x, y; init_func(); for (x=0; x<3; x++) { for (y=0; y< 3; y++) { printf("--- x=%d, y=%d ---\n",x ,y); funcbox[x][y](); } } return 0; }
以下にサンプルソースを簡単に説明します。
typedef void (*FUNCP)(void);
FUNCP funcbox[3][3];
funcbox[0][0] = &func_0_0; /* x=0, y=0 */ funcbox[0][1] = &func_0_1; /* x=0, y=1 */ funcbox[0][2] = &func_0_2; /* x=0, y=2 */ funcbox[1][0] = &func_1_0; /* x=1, y=0 */ funcbox[1][1] = &func_1_1; /* x=1, y=1 */ funcbox[1][2] = &func_1_2; /* x=1, y=2 */ funcbox[2][0] = &func_2_0; /* x=2, y=0 */ funcbox[2][1] = &func_2_1; /* x=2, y=1 */ funcbox[2][2] = &func_2_2; /* x=2, y=2 */
for (x=0; x<3; x++) { for (y=0; y< 3; y++) { printf("--- x=%d, y=%d ---\n",x ,y); funcbox[x][y](); } }
Cygwinのgccを利用してコンパイルおよび実行してみます。
sakurat@winpc ~ $ gcc matrix.c -o matrix sakurat@winpc ~ $ ./matrix --- x=0, y=0 --- func_0_0 --- x=0, y=1 --- func_0_1 --- x=0, y=2 --- func_0_2 --- x=1, y=0 --- func_1_0 --- x=1, y=1 --- func_1_1 --- x=1, y=2 --- func_1_2 --- x=2, y=0 --- func_2_0 --- x=2, y=1 --- func_2_1 --- x=2, y=2 --- func_2_2
以上、関数のポインタ配列に関数を設定し呼び出すサンプルソースでした。