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

前端 未结 14 2741
执念已碎
执念已碎 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:36

    You declare int array[10] means array has index 0 to 9 (total 10 integer elements it can hold). But the following loop,

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

    will loop 0 to 10 means 11 time. Hence when i = 10 it will overflow the buffer and cause Undefined Behavior.

    So try this:

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

    or,

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

提交回复
热议问题