Reputation: 103
I was writing a program in which i used a 5x5 array, and i actually came up with a bug.
In order to find it, I tried simplifying the program, and writing another one instead, in which i just wanted to simply show the numbers 1 to 25 using arrays.
#include <iostream>
#include <conio.h>
using namespace std;
main()
{
long int a[4][4];
int m=1;
for(int i=0;i<5;i++)
{for(int j=0;j<5;j++)
{a[i][j]=m;
m=m+1;
}
}
for(int i=0;i<5;i++)
{for(int j=0;j<5;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
getch();
}
And what i actually got was this:
1 2 3 4 6
6 7 8 9 11
11 12 13 14 16
16 17 18 19 21
21 22 23 24 25
However, when i tried a different thing and put a cout<<a[i][j];
after a[i][j]=m;
and deleted the second part, i got it correct.
Am i missing something here?
Upvotes: 0
Views: 175
Reputation: 1781
when you are declaring a[4][4] it is actually creating a 4X4 matrix that is a matrix that can contain maximum of 16 values, the numbers in the square brackets are to mention size of array. Size is given in as humans count like 1,2,3,4... and the index value from where the program starts storing the input starts from 0. so from here you can conclude that
a[ 1 ] (what we see or think) For computer is a[0]
a[2] (what we see or think) For computer is a[ 1 ]
a[3] (what we see or think) For computer is a[2]
and so on...
in your code change
a[4][4]
to
a[5][5]
Upvotes: 1
Reputation: 103693
Your array is 4 by 4, but you are treating it as though it is 5 by 5. Your code has undefined behavior. Your loop should only count until i < 4
and j < 4
, or you need to declare your array as long int a[5][5];
.
By the way, main
should have a return type, and it should be int
. Anything else is non-standard.
Upvotes: 4