このサンプルプログラムの結果がなぜH*e*l*l*o*になるのかがわかりません・・・
str[5]には¥0が入っていると思います。
while(str)←これがなぜ¥0でない限り繰り返すという命令になっているんですか?
o*を表示した後に、iには5が入ると思います。
while(str)が真となり再びループになると思うのですが・・・
配列がよくわかりません・・・
Re: 配列がよくわかりません・・・
(以下、引用はN1256より)
文字列リテラルの最後にはゼロで表される文字が追加されます。
char str[]は要素数のわかっていない配列なので、末尾のヌル文字までが初期化に使用され、strに格納されます。
初期化より、配列strの要素は となっています。従って、i=5のとき、str、すなわち配列strの5番目の要素は0です。
while文は、条件が0になるまでループする内容を繰り返し実行します。
裏を返せば、条件式が0になれば繰り返しは終了します。
したがって、i=5になると、strは0になるので、ループが終了します。
文字列リテラルの最後にはゼロで表される文字が追加されます。
ゼロで表される文字はヌル文字と呼ばれます。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に格納されます。
strは*((str)+(i))と等価であり、配列strのi番目の要素になります。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.
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の要素は となっています。従って、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で殴ればいい!(死亡フラグ)
Re: 配列がよくわかりません・・・
おおおお!みけCATさん!わかりやすく教えていただきありがとうございました!!!わかりました!条件式が0になるので終わりなんですね!