開発環境
- OS: macOS High Sierra - Apple
- Text Editor: Emacs
- コンパイラー: LLVM/Clang, GCC(gcc)
- プログラミング言語: C
Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の7章(高度な関数 - 関数を最大限に活用する)、長いエクササイズ(p. 328)を取り組んでみる。
長いエクササイズ(p. 328)
Makefile
CC = cc all: run sample: sample.c $(CC) sample.c -o sample run: sample ./sample
#include <stdio.h> #include <stdlib.h> #include <string.h> int scores_n = 7; int scores[] = {543, 323, 32, 554, 11, 3, 112}; void scores_display() { puts(__func__); for (int i = 0; i < scores_n; i++) { printf("%i\n", scores[i]); } } int compare_scores(const void *score_a, const void* score_b) { int a = *(int*)score_a; int b = *(int*)score_b; return a - b; } int compare_scores_desc(const void* score_a, const void* score_b) { return compare_scores(score_b, score_a); } typedef struct { int width; int height; } Rectangle; int rects_n = 5; Rectangle rects[] = { {1, 1}, {1, 5}, {1, 2}, {1, 4}, {1, 3} }; void rects_display() { puts(__func__); for (int i = 0; i < rects_n; i++) { printf("%i x %i\n", rects[i].width, rects[i].height); } } int compare_areas(const void* a, const void* b) { Rectangle *rect_a = (Rectangle*)a; Rectangle *rect_b = (Rectangle*)b; int area_a = rect_a->width * rect_a->height; int area_b = rect_b->width * rect_b->height; return area_a - area_b; } int names_n = 5; char *names[] = { "a", "e", "b", "d", "c" }; void names_display() { puts(__func__); for (int i = 0; i < names_n; i++) { puts(names[i]); } } int compare_names(const void *a, const void* b) { char **name_a = (char**)a; char **name_b = (char**)b; return strcmp(*name_a, *name_b); } int compare_areas_desc(const void*a, const void*b) { return compare_areas(b, a); } int compare_names_desc(const void* a, const void* b) { return compare_names(b, a); } int main() { scores_display(); qsort(scores, scores_n, sizeof(int), compare_scores); scores_display(); qsort(scores, scores_n, sizeof(int), compare_scores_desc); scores_display(); rects_display(); qsort(rects, rects_n, sizeof(Rectangle), compare_areas); rects_display(); qsort(rects, rects_n, sizeof(Rectangle), compare_areas_desc); rects_display(); names_display(); qsort(names, names_n, sizeof(char*), compare_names); names_display(); qsort(names, names_n, sizeof(char*), compare_names_desc); names_display(); }
入出力結果(Terminal)
$ make cc sample.c -o sample ./sample scores_display 543 323 32 554 11 3 112 scores_display 3 11 32 112 323 543 554 scores_display 554 543 323 112 32 11 3 rects_display 1 x 1 1 x 5 1 x 2 1 x 4 1 x 3 rects_display 1 x 1 1 x 2 1 x 3 1 x 4 1 x 5 rects_display 1 x 5 1 x 4 1 x 3 1 x 2 1 x 1 names_display a e b d c names_display a b c d e names_display e d c b a $
0 コメント:
コメントを投稿