This program stops unexpectedly after reaching 'Person 57'. What is the reason?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
using namespace std;

void main()
{
	int array[10];
	int i=0,j,c=0;

	for(i=0,j=1;i<100;i++,j++)
	{
		cout<<"No. of pancakes person "<<j<<" ate: ";
		cin>>array[i];

		if(i==-1)
			i=10000;
	}

		
	for(i=0;i<10;i++)
	{
		if(c<array[i])
		{
			c=array[i];
			j=i+1;
		}
	}
	cout<<"\nPerson "<<j<<" ate "<<c<<" pancakes. \n\n";
}


Why does this program stop unexpectedly after reaching 'Person 57' on execution?
Last edited on
size of array is 10 but i goes up to 100 ? how do you expect that to work..

notes:
lines 14, 15 don't do anything. i will never be -1.
line 11: you don't need a separate counter for that. just << i+1 << ...;
okay i know about that, but why '57' ?! :|
closed account (jw6XoG1T)
first off ur using the wrong variable type. use Strings
closed account (jw6XoG1T)
sorry wrong post lol
Once you start writing past the end of an array, your code enters the realm of "undefined behavior." When you hit 57 you happen hit a point in memory that your system knows you cannot legally write to.

It will be a different number on other OSes, with other compilers, and other architectures.

If you had a more complicated program, you could cause a crash at 12. Or 16. Or you would cause no crash at all, but suddenly your program starts misbehaving in other unpredictable ways. Or you may never see it until you recompile with a new compiler or apply an OS patch.
Topic archived. No new replies allowed.