Head First C ―頭とからだで覚えるCの基本
(オライリージャパン)
David Griffiths (著) Dawn Griffiths (著)
中田 秀基(監訳)(翻訳) 木下 哲也 (翻訳)
開発環境
- OS X Yosemite - Apple (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- LLVM/Clang (コンパイラ, Xcode - Apple)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の7章(高度な関数: 関数を最大限に活用する)、長いエクササイズ(p.328)を解いてみる。
その他参考書籍
- 21st Century C: C Tips from the New School
- プログラミング言語C 第2版 ANSI規格準拠(B.W. カーニハンD.M. リッチー(著)、石田 晴久(翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
- C実践プログラミング 第3版(Steve Oualline(著)、望月 康司 (監訳)(翻訳)、谷口 功(翻訳)、 オライリージャパン)
長いエクササイズ(p.328)
コード(BBEdit, Emacs)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare_scores_desc(const void *score_a, const void *score_b) {
return *(int *)score_b - *(int *)score_a;
}
typedef struct {
int width;
int height;
} rectangle_s;
int compare_areas(const void *a, const void *b) {
rectangle_s *a_rec = (rectangle_s *)a;
rectangle_s *b_rec = (rectangle_s *)b;
return a_rec->width * a_rec->height - b_rec->width * a_rec->height;
}
int compare_names(const void *a, const void *b) {
return strcmp(*((char **)a), *((char **)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() {
int scores[] = {5, 1, 4, 2, 3};
rectangle_s recs[] = {(rectangle_s){.width = 1, .height = 5},
(rectangle_s){.width = 1, .height = 1},
(rectangle_s){.width = 4, .height = 5},
(rectangle_s){.width = 2, .height = 5},
(rectangle_s){.width = 3, .height = 5}};
char *names[] = {"ab", "Ab", "aB", "AB"};
qsort(scores, 5, sizeof(int), compare_scores_desc);
for (int i = 0; i < 5; i++)
printf("%d ", scores[i]);
printf("\n");
qsort(recs, 5, sizeof(rectangle_s), compare_areas);
for (int i = 0; i < 5; i++)
printf("%dx%d ", recs[i].width, recs[i].height);
printf("\n");
qsort(recs, 5, sizeof(rectangle_s), compare_areas_desc);
for (int i = 0; i < 5; i++)
printf("%dx%d ", recs[i].width, recs[i].height);
printf("\n");
qsort(names, 4, sizeof(char *), compare_names);
for (int i = 0; i < 4; i++)
printf("%s ", names[i]);
printf("\n");
qsort(names, 4, sizeof(char *), compare_names_desc);
for (int i = 0; i < 4; i++)
printf("%s ", names[i]);
printf("\n");
}
入出力結果(Terminal)
p$ crun.sh sample328 clang ... 5 4 3 2 1 1x5 1x1 2x5 3x5 4x5 4x5 3x5 2x5 1x5 1x1 AB Ab aB ab ab aB Ab AB $
0 コメント:
コメントを投稿