C++ output question

Hi, I am not sure why the output of the double array r[][] is different the two times I call it. In the example below, i have set r[i][j] = i+j. Then I output it in two different loops and find that it does not output the same numbers.

int main()
{
int i,j,k;
double **r;

i=0;
r = new double*[5];
for(i=0;i<5;i++)
{
r[i] = new double[i+1];
for(j=i;j<5;j++)
{
r[i][j] = i+j;
cout << (r[i][j]) << endl; //This works
}
cout << endl;
}


i=0;
for(i=0;i<5;i++)
{
for(j=i;j<5;j++)
{
cout << (r[i][j]) << endl; //This does not!
}
cout << endl;
}


/*

i=0;
mytree.m = 5;
mytree.p = new double*[mytree.m];
for(i=0;i<mytree.m;i++)
{
mytree.p[i] = new double[i+1];
for(j=i;j<mytree.m;j++)
{
mytree.p[i][j] = i+j;
cout << mytree.p[i][j] << " " << "(" << i << "," << j << ")" << endl;
}
}

*/

cout << endl;

//k=0;
//mytree.p[2][3] = k;
//mytree.p[3][3] = k;
//mytree.p[2][2] = (mytree.p[2][3] + mytree.p[3][3]);


system("PAUSE");
return 0;
}
Last edited on
You are accessing outside of your array bounds and are corrupting the heap as a result.

1
2
3
4
5
6
7
r = new double*[5];
for(i=0;i<5;i++)
{
  r[i] = new double[i+1];  // r[0] is only 1 element large
  for(j=i;j<5;j++)
  {
    r[i][j] = i+j;  // yet you are accessing r[0][4] -- OUT OF BOUNDS 
Got it. Thanks very much.
Topic archived. No new replies allowed.