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

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

    When you iterate past i==9 you assign zero to the 'array items' which are actually located past the array, so you're overwritnig some other data. Most probably you overwrite the i variable, which is located after a[]. That way you simply reset the i variable to zero and thus restart the loop.

    You could discover that yourself if you printed i in the loop:

          printf("test i=%d\n", i);
    

    instead of just

          printf("test \n");
    

    Of course that result strongly depends on the memory allocation for your variables, which in turn depends on a compiler and its settings, so it is generally Undefined Behavior — that's why results on different machines or different operating systems or on different compilers may differ.

    0 讨论(0)
  • 2020-12-12 09:59

    I will suggest something that I dint find above:

    Try assigning array[i] = 20;

    I guess this should terminate the code everywhere.. (given you keep i< =10 or ll)

    If this runs you can firmly decide that the answers specified here already are correct [the answer related to memory stomping one for ex.]

    0 讨论(0)
提交回复
热议问题