0

I was trying to test what output I would get when I tried to print the array that the index goes out of bound.

The code:

#include <stdio.h>

void main()
{

    int arr[] = { 3, 4, 5 };

    for (int i = 0; i < 5; i++)
    {
        if (arr[i] == 0)
        {
            printf("Breaking out of the loop.");
            break;

        }

        else
            printf("%i\n", arr[i]);
    }


    getchar();
}

When I run this code, the output is:

3
4
5
-858993460
3997200

I expected it to print out "Breaking out of the loop" and break out of the loop and terminate. I truly have no idea how it even printed those numbers.

Any idea what those numbers mean?

P.S. I am sorry if this is a stupid question, I am quite new to C.

James
  • 176
  • 1
  • 4
  • 16

1 Answers1

2

Memory out of bounds of an array, or dynamically allocated memory, doesn't belong to you, and its content is indeterminate. Accessing arrays or memory out of bounds leads to undefined behavior. Just don't do it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621