- 追加された行はこの色です。
- 削除された行はこの色です。
#navi(../)
* 関数のポインタのサンプルとマトリックスで使う [#xc9cf835]
C言語では、関数のポインタ変数を宣言し、関数を変数に代入しその変数を関数として使用することができます。~
本記事では、関数のポインタの2次元配列を作成し、マトリックスとして利用できる方サンプルを記します。
関数のポインタを2次元配列に入れることにより、X,Yにて関数を呼び出すことができます。~
状態遷移が複雑なプログラムなど、switch case を多用しなくても、X,Yという二つの状態を管理しておけば、~
状態に対応した関数を呼び出すことができます。
#htmlinsertpcsp(c-top.html,c-sp.html)
#contents
* サンプルソース [#p7998b77]
マトリックスのC言語サンプルソースを以下に記します。
#ref(matrix.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;
}
以下にサンプルソースを簡単に説明します。
-関数のポインタ型 FUNCP を宣言しています。~
FUNCPという名前で引数なしで関数のポインタ宣言をしています。
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,yを変化させ、関数のポインタ配列に格納されている関数を呼び出しています。
for (x=0; x<3; x++) {
for (y=0; y< 3; y++) {
printf("--- x=%d, y=%d ---\n",x ,y);
funcbox[x][y]();
}
}
* 実行結果 [#h6d451c8]
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
以上、関数のポインタ配列に関数を設定し呼び出すサンプルソースでした。
#htmlinsertpcsp(c-btm.html,c-sp.html)