Why does this for loop exit on some platforms and not on others?

前端 未结 14 2730
执念已碎
执念已碎 2020-12-12 09:00

I have recently started to learn C and I am taking a class with C as the subject. I\'m currently playing around with loops and I\'m running into some odd behaviour which I d

14条回答
  •  自闭症患者
    2020-12-12 09:40

    You have a bounds violation, and on the non-terminating platforms, I believe you are inadvertently setting i to zero at the end of the loop, so that it starts over again.

    array[10] is invalid; it contains 10 elements, array[0] through array[9], and array[10] is the 11th. Your loop should be written to stop before 10, as follows:

    for (i = 0; i < 10; i++)
    

    Where array[10] lands is implementation-defined, and amusingly, on two of your platforms, it lands on i, which those platforms apparently lay out directly after array. i is set to zero and the loop continues forever. For your other platforms, i may be located before array, or array may have some padding after it.

提交回复
热议问题