array !!

I set 2 places in array called a .
despite i put for loop exceeds than my array, it works correctly and give me the answer of a[5] correct !! how does array work in this situation?

then why i put a[2] even it will work for 5??


1
2
3
4
5
6
7
8
  void main ()
{
	int a[2];
	for (int i =0; i<=5;i++)
	cin>>a[i];

	cout<<a[5];
}
If you assign more values in your array than its size, it will generate "undefined" behavior.

In your simple case, it seems that you can still print out a[5] as desired since you are not exceeding the array size too much. However, when you try the following, the program will crash.

1
2
3
4
5
const int NUMBER = 500;      // exceeds the size of the array too much
int a[2];
for (int i = 0; i < NUMBER ; i++)
   a[i] = i;
cout << a[NUMBER];


See more discussion on
http://stackoverflow.com/questions/1239938/c-accesses-an-array-out-of-bounds-gives-no-error-why
Last edited on
thank you so much :)
Topic archived. No new replies allowed.