開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第5章(ポインタと配列)、5.6(ポインタ配列: ポインタへのポインタ)、演習5-7を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 5-7.
コード
sample.c
#include <stdio.h> #include <string.h> #define MAXLINES 5000 #define SIZE 10000 char *lineptr[MAXLINES]; int readlines(char *lineptr[], int nlines, char *buf); void writelines(char *lineptr[], int nlines); void qsort(char *lineptr[], int left, int right); void swap(char *v[], int i, int j); int main() { int nlines; char buf[SIZE]; if ((nlines = readlines(lineptr, MAXLINES, buf)) >= 0) { qsort(lineptr, 0, nlines-1); writelines(lineptr, nlines); return 0; } else { printf("error: input too bi to sort\n"); return 1; } } int my_getline(char *line, int max); int my_getline(char *s, int lim) { int c; char *t = s; while (--lim > 0 && (c=getchar()) != EOF && c != '\n') *s++ = c; if (c == '\n') *s++ = c; *s = '\0'; return s - t; } #define MAXLEN 1000 int readlines(char *lineptr[], int maxlines, char *buf) { int len, nlines; char line[MAXLEN]; char *p = buf; nlines = 0; while ((len = my_getline(line, MAXLEN)) > 0) { if (nlines >= maxlines || p + len > buf + SIZE) return -1; else { line[len-1] = '\0'; strcpy(p, line); lineptr[nlines++] = p; p += len; } } return nlines; } void writelines(char *lineptr[], int nlines) { int i; for (i = 0; i < nlines; i++) printf("%s\n", lineptr[i]); } void qsort(char *v[], int left, int right) { int i, last; void swap(char *v[], int i, int j); if (left >= right) return; swap(v, left, (left + right) / 2); last = left; for (i = left+1; i <= right; i++) if (strcmp(v[i], v[left]) < 0) swap(v, ++last, i); swap(v, left, last); qsort(v, left, last-1); qsort(v, last+1, right); } void swap(char *v[], int i, int j) { char *temp; temp = v[i]; v[i] = v[j]; v[j] = temp; }
入出力結果(Terminal)
$ cat sample.txt Ah Love! could you and I with Fate conspire To grasp this sorry Scheme of Things entire, Would not we shatter it to bits -- and then Re-mould it nearer to the Heart's Desire! $ cat sample.txt | ./a.out Ah Love! could you and I with Fate conspire Re-mould it nearer to the Heart's Desire! To grasp this sorry Scheme of Things entire, Would not we shatter it to bits -- and then $
0 コメント:
コメントを投稿