The value of array outside the domain

Dear all,
In the following program, I have initialize the value of compound array to 10 (where j=3 is not included), then I put the value of array beyond the limit (j=3) equal to zero.
When I print the value of the full array the values of first column has also become zero. Can some body please comment on this problem.

#include<iostream>
using namespace std;

int main ()
{
const int grid=3;
int i,j; // Defining variable
int array[grid+1][grid]; // Defining an array

for (i=0; i<=grid; i++)
{
for (j=0; j<grid; j++)
{
array[i][j]= 10; // Initialization of the array
}
}
for (i=0; i<=grid; i++)
{
for (j=0; j<grid; j++)
{
cout<<array[i][j]<<"\t"<<i<<"\t"<<j<<endl; // Printing of the array
}
}
cout<<endl;

for (i=0; i<=grid; i++)
{
if(j==3)
{
array[i][j]= 0;
cout<<"\t"<<i<<"\t"<<j<<endl; // Assigning array for outside the domain equal to zero.
}
}
cout<<endl;
for (i=0; i<=grid; i++)
{
for (j=0; j<grid; j++)
{
cout<<array[i][j]<<"\t"<<i<<"\t"<<j<<endl;
}
}
return 0;
}
Last edited on
What you are doing is an error and is considered "undefined behavior", so in theory anything can happen. In practice it is simply writing one element beyond j=2 which, since the rows are stored contiguously, is the first element in the next row.

BTW, use code tags to post code (note the <> button to the right).
Last edited on
Topic archived. No new replies allowed.