0
int a[5] = {1,2,3,4,5};

for (int i = 0; a[i]; i++)
{
    cout << i;

}

このコードは、「0 1 2 3 4」の出力を生成します。a[i] を何と比較し、どのようにして配列の最後で停止し、超えないようにするのでしょうか?

4

3 に答える 3

3

あなたのコードは未定義の動作を引き起こします。式a[i]は、ゼロ以外の場合は true として評価され、ゼロの場合は false として評価されます。それを実行すると、0メモリ内の配列の直後に単語があるというラッキーなことになり、ループが停止します。

于 2013-10-09T01:26:38.393 に答える
0

それは配列を通り過ぎて読み込んでおり、運が良かっただけで、そこにあるメモリはたまたまゼロになっています。その配列の末尾を超えて読み取ることは未定義の動作であり、結果はいつでも変わる可能性があるため、決してそれに依存しないでください。

于 2013-10-09T01:26:45.273 に答える
0

You can think of a[i] as being compared to 0, it simply fetches the number retrieved from the location in memory and if 0 is the value that lives at that memory, then the loop exits, if it is any other number the loop continues.

Suppose an int is 4 bytes on the system. a is given an address, lets pretend it is 0xFF00 when we try to evaluate a[0] we retrieve the data value stored at memory 0xFF00. a[1] would retrieve data from memory 0xFF04, etc. Your program only assigns values to the first 5 memory locations, so when we retrieve the data at beyond these locations they could be anything from 0 to INT_MAX. If it happens to be 0 then the loop exits, however if it happens to be something else the loop continues.

Your could adjust your program like so to see it better:

#include <iostream>
using namespace std;
int main() {
    int a[5] = {1,2,3,4,5};
    int i;
    for (i = 0; a[i]; i++)
    {
        cout << "At memory address: " << &a[i]
             << " lives the value: " << a[i] << endl;
    }
    cout << "At memory address: " << &a[i]
         << " lives the value: " << a[i]
         << ", and this is why the loop ended." << endl;
    return 0;
}
于 2013-10-09T01:42:17.643 に答える