0

I feel really dumb, but I don't get how sometimes in C, I can have:

int i[2];
i[2] = 3; 
printf("%d, i[2]); 

and it'll still output 3. Shouldn't this be outputting junk/give an error since i[2] is out of bound? (using gcc if that makes a difference, as I've been testing this on online editors and they thankfully return an error..)

Rayden
  • 1
  • its undefined behavior, anything can happen, try doint the printf twice in a row , see what happens – pm100 Nov 04 '22 at 22:29

1 Answers1

1

Defining an array, or any object, reserves memory for it. Using an index out of bounds attempts to use memory not reserved for the array. The behavior of that is not defined by the C standard.

If you bought several lots of land and started building on the wrong one, somebody might notice right away and stop you, or nobody might notice for a long time.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312