C - 高度な関数 - 関数を最大限に活用する - 関数ポインタの作成方法
Head First C ―頭とからだで覚えるCの基本、 David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の 7章(高度な関数 - 関数を最大限に活用する)、p.321(エクササイズ)の解答を求めてみる。
Makefile
main: main.c
cc main.c && ./a.out
コード
main.c
#include <stdio.h>
#include <string.h>
int NUM_ADS = 7;
char *ADS[] = {
"William: SBM GSOH likes sports, TV, dining",
"Matt: SWM NS likes art, movies, theater",
"Luis: SLM ND likes books, theater, art",
"Mike: DWM DS likes trucks, sports and bieber",
"Peter: SAM likes chess, working out and art",
"Josnh: SJM likes sports, movies and theater",
"Jed: DBM likes theater, books and dining"};
int sports_no_bieber(char *s)
{
return strstr(s, "sports") && !strstr(s, "bieber");
}
int sports_or_workout(char *s)
{
return strstr(s, "sprots") || strstr(s, "working out");
}
int ns_theater(char *s)
{
return strstr(s, "NS") && strstr(s, "theater");
}
int arts_theater_or_dining(char *s)
{
return strstr(s, "art") || strstr(s, "theater") || strstr(s, "dining");
}
void find(int (*match)(char *))
{
puts("検索結果");
puts("--------------------");
for (int i = 0; i < NUM_ADS; i++)
{
if (match(ADS[i]))
{
printf("%s\n", ADS[i]);
}
}
puts("--------------------");
}
int main()
{
int (*matchs[])(char *) = {sports_no_bieber,
sports_or_workout,
ns_theater,
arts_theater_or_dining,
NULL};
for (size_t i = 0; matchs[i] != NULL; i++)
{
printf("%p\n", matchs[i]);
find(matchs[i]);
}
}
入出力結果(Terminal, Zsh)
% make
cc main.c && ./a.out
検索結果
--------------------
Josnh: SJM likes sports, movies and theater
--------------------
%