配列がよくわかりません・・・

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
アバター
エルフ
記事: 79
登録日時: 9年前
住所: 埼玉

配列がよくわかりません・・・

#1

投稿記事 by エルフ » 8年前

このサンプルプログラムの結果がなぜH*e*l*l*o*になるのかがわかりません・・・
str[5]には¥0が入っていると思います。
while(str)←これがなぜ¥0でない限り繰り返すという命令になっているんですか?
o*を表示した後に、iには5が入ると思います。
while(str)が真となり再びループになると思うのですが・・・

コード:

#include <stdio.h>

int main(void)
{
	char str[] = "Hello";
	int i=0;
	while(str[i])
	{
		printf("%c*", str[i]);
		i++;
	}
}

アバター
みけCAT
記事: 6734
登録日時: 13年前
住所: 千葉県
連絡を取る:

Re: 配列がよくわかりません・・・

#2

投稿記事 by みけCAT » 8年前

(以下、引用はN1256より)

文字列リテラルの最後にはゼロで表される文字が追加されます。
6.4.5 String literals さんが書きました: 5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.
ゼロで表される文字はヌル文字と呼ばれます。
5.2.1 Character sets さんが書きました: A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string.
文字の配列は文字列リテラルによって初期化することができます。
char str[]は要素数のわかっていない配列なので、末尾のヌル文字までが初期化に使用され、strに格納されます。
6.7.8 Initialization さんが書きました: 14 An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
strは*((str)+(i))と等価であり、配列strのi番目の要素になります。
6.5.2.1 Array subscripting さんが書きました: 2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).


初期化より、配列strの要素は

コード:

0   1   2   3   4   5
'H' 'e' 'l' 'l' 'o' 0
となっています。従って、i=5のとき、str、すなわち配列strの5番目の要素は0です。

while文は、条件が0になるまでループする内容を繰り返し実行します。
6.8.5 Iteration statements さんが書きました: 4 An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. The repetition occurs regardless of whether the loop body is entered from the iteration statement or by a jump.
6.8.5.1 Thewhilestatement さんが書きました: 1 The evaluation of the controlling expression takes place before each execution of the loop
body.


裏を返せば、条件式が0になれば繰り返しは終了します。
したがって、i=5になると、strは0になるので、ループが終了します。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

アバター
エルフ
記事: 79
登録日時: 9年前
住所: 埼玉

Re: 配列がよくわかりません・・・

#3

投稿記事 by エルフ » 8年前

おおおお!みけCATさん!わかりやすく教えていただきありがとうございました!!!わかりました!条件式が0になるので終わりなんですね!

アバター
エルフ
記事: 79
登録日時: 9年前
住所: 埼玉

Re: 配列がよくわかりません・・・

#4

投稿記事 by エルフ » 8年前

またよろしくお願いします。

閉鎖

“C言語何でも質問掲示板” へ戻る