How do I dynamically allocate memory to a double pointer in an object

I am trying to create an object which allocates memory to a lower triangular matrix of doubles. The memory needs to be allocated dynamically. The following code does not work and I am not sure why. Can soneone help out.

class tree{
public:
int m;
double **p;
};

int main()
{
tree mytree;
int i,j;

mytree.m = 5;
cout << mytree.m << endl; // This works

i=0;
for(i=0;i<mytree.m;i++)
{
mytree.p[i] = new double[i+1]; //This works
for(j=0;j<=i;j++)
{
mytree.p[i][j] = .5; //Gets stuck here

cout << mytree.p[i][j] << " ";
}
cout << endl;
}
system("PAUSE");
return 0;
}
Last edited on
I think it should be mytree.p[i] = new double*[i+1];

Nevermind that. You need initialize p before using it. E.g, mytree.p = new double*[mytree.m];
Last edited on
Works! Thanks a lot.
Topic archived. No new replies allowed.