開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang (コンパイラ)
C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅢ部(高度なプログラミング概念)の17章(高度なポインタ)、17-12(プログラミング実習)、実習17-2.を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
17-12(プログラミング実習)、実習17-2.
コード
sample.c
#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> struct linked_list{ char data[30]; struct linked_list *next_ptr; }; struct linked_list *first_ptr = NULL; void memory_error() { fprintf(stderr, "Error:Out of memory\n"); exit (8); } void add(char *item) { struct linked_list *new_item_ptr; new_item_ptr = malloc(sizeof(struct linked_list)); if(new_item_ptr == NULL){ memory_error(); } strcpy(new_item_ptr->data, item); new_item_ptr->next_ptr = first_ptr; first_ptr = new_item_ptr; } void delete(char *item) { struct linked_list *current_ptr; struct linked_list *prev_ptr; current_ptr = first_ptr; prev_ptr = NULL; while (current_ptr != NULL){ if(strcmp(current_ptr->data, item) == 0){ if(prev_ptr == NULL){ first_ptr = current_ptr->next_ptr; } else { prev_ptr->next_ptr = current_ptr->next_ptr; } free(current_ptr); } prev_ptr = current_ptr; current_ptr = current_ptr->next_ptr; } } void print_linked_list(struct linked_list *l_ptr) { if (l_ptr == NULL){ printf("\n"); return; } printf("%s ", l_ptr->data); print_linked_list(l_ptr->next_ptr); } int main(int argc, char *argv[]) { char *words[] = {"python", "c", "scheme", "haskell", "dart"}; int i; for(i = 0; i < 5; i++){ add(words[i]); } print_linked_list(first_ptr); delete("c"); print_linked_list(first_ptr); delete("python"); print_linked_list(first_ptr); delete("dart"); print_linked_list(first_ptr); delete("scheme"); delete("haskell"); if(first_ptr == NULL){ printf("空っぽ\n"); } else { print_linked_list(first_ptr); } return (0); }
makefile
CC=cc CFLAGS=-g sample: sample.c $(CC) $(CFLAGS) -o sample sample.c clean: rm -f sample
入出力結果(Terminal)
$ ./sample dart haskell scheme c python dart haskell scheme python dart haskell scheme haskell scheme 空っぽ $
0 コメント:
コメントを投稿