Why is there an infinite loop in my program?

后端 未结 5 735
再見小時候
再見小時候 2021-01-04 16:15
int main(void)
{
    int i;
    int array[5];

    for (i = 0; i <= 20; i++)
    array[i] = 0;

    return 0;
}

Why is the above code stuck in a

5条回答
  •  感动是毒
    2021-01-04 16:46

    You declare an array with 5 elements but write 21 elements to it. Writing past the end of an array results in undefined behaviour. In you case, you're writing to the loop counter i, resetting it to 0, probably when you assign array[5].

    If you want to fix your program, change the loop to write to the correct number of elements

    int num_elems = sizeof(array) / sizeof(array[0]);
    for (i = 0; i < num_elems ; i++)
    

提交回复
热议问题