-1

I am curious about below code in C

int main(){

        int arr[10];
        *(arr+120) = 5;
        int *px = arr;
        int i = 0;
        for(i = 0; *px != 5; px++){
          i++;
        }

        printf("%d", i);
}

This code produced output of 120. Our array is said to hold 10 items. How can I assign some value for index 120, run loop and get my value if there potentially should be some kind of error. Probably I am not getting some C language specifics. In java I would get OutOfBounds exception.... Please, help to clarify it. Thank you!

1 Answers1

3

C does not check array bounds, and the code accessing out-of-array elements is undefined behaviour, which means that anything may happen - including the result you got.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51