開発環境
- OS X Lion - Apple (UNIX) (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang (コンパイラ)
C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅡ部(単純なプログラミング)の9章(変数スコープおよび関数)、9.1(スコープおよびクラス)、9.2(関数)、9.3(パラメータをとらない関数)、設問 9-1を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
設問 9-1.
return 文がfor loopのブロック内にあり、indexをカウントアップすることなく初期化した値0を返すことになるから、どの文字列に付いても長さ0という結果になる。
retunがforループのブロックの外になるように。修正。
コード
sample.c
#include <stdio.h> int length(char string[]) { int index; for (index = 0; string[index] != '\0'; ++index){ /* 何もしない */ } return (index); } int main() { char line[100]; while (1){ printf("Enter line: "); fgets(line, sizeof(line), stdin); printf("Length (including newlinew) is : %d\n", length(line)); } return (0); }
makefile
CC=cc CFLAGS=-g sample: sample.c $(CC) $(CFLAGS) -o sample sample.c clean: rm -f sample
入出力結果(Terminal)
$ make cc -g -o sample sample.c $ ./sample Enter line: 1 Length (including newlinew) is : 2 Enter line: 12 Length (including newlinew) is : 3 Enter line: 123 Length (including newlinew) is : 4 Enter line: 1234 Length (including newlinew) is : 5 Enter line: 12345 Length (including newlinew) is : 6 Enter line: ^C $
0 コメント:
コメントを投稿