How could it be possible to read and write past the array

后端 未结 3 2068
一整个雨季
一整个雨季 2020-12-12 05:42

Output of the program:

#include 

int main()
{
    int size;

    printf(\"Enter the size of array: \");
    scanf(\"%d\",&size);

    i         


        
3条回答
  •  庸人自扰
    2020-12-12 06:33

    In your loop, the condition i < size is checked before i is incremented. But, i is incremented before entering the body of the loop and not after it, so it is possible to access b[5] in this case, as i would be incremented after checking i < size with i=4. You do not want that, as this causes undefined program behavior.

    If you try to access an element in the array which does not exist, e.g. array[size], you are accessing the next spot in the memory right after the array. In this case you are lucky, but if this meant you were accessing a part of the memory where your program isn't allowed to do so, you'd get a segmentation fault.

提交回复
热议问题