In the program below, when I input a number bigger than 99 for variable N, N changes its value during the execution. When I input a small number, it does not!
Why is that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include "stdafx.h"
int N, K, MAPA[101][101];
int main() {
scanf("%i %i", &N, &K);
printf("%i\n\n", N);
for (int a = 1; a < N+2; a++) {
for (int b = 1; b < N+2; b++) {
MAPA[a][b] = 0;
}
}
printf("%i", N );
return 1;
}
So would this mean that memory location of N is next to the last element of the MAPA array and that is causing it to be set to 0?
Yes, it is assigning 0 at the memory location that happens to be where N is at. By moving the declaration of N somewhere else this wouldn't happen, but you still have the out of bounds problem.
Only on some systems (particularly little-endian.) Don't rely on this behavior! Accessing (dereferencing and/or changing the value of) memory that's out of bounds is unsupported and causes undefined behavior.