Why does N keep changing its value?

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;
} 




EXAMPLES:
IN
200 200
OUT
200

0


IN
4 4
OUT
4

4
you are out of the bounds of that array with the large numbers, you define the size as 101.
But if I input 100 100 I get the same output:

100

0

So, it does not make sense.
Last edited on
you are out of the bounds of that array with the large numbers, you define the size as 101.


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?
100 + 2 == 102 (Out of bounds)
An array with size 101 has indexes 0-100...
But if I input 100 100 I get the same output:

That is because 100 + 2 = 102

for (int a = 1; a < N+2; a++)

resulting in... after last iteration of the for loop
a = 101

Remeber c++ is 0 based index, so a size of 101 elements are indexed 0-100. 101 is out of bounds
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.
Topic archived. No new replies allowed.