I would like to create something like a pointer to a 2 dimensional array of pointers (with the width and the height of x
).
Will this code do what I expect? (Create array elements, writing out some information about them, then release all the allocated memory.)
int main(int argc, char** argv) {
int x = 3;
Node ***array = new Node**[x];
for (int i = 0; i < 3; i++) {
array[i] = new Node*[x];
for (int j = 0; j < x; j++) {
array[i][j] = new Node(i, j); /* Node::Node(int row, int col) */
}
}
/* ....... */
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
cout << array[i][j]->row << ", " << array[i][j]->col << endl;
}
}
/* ....... */
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
delete array[i][j];
//array[i][j] = NULL;
}
delete[] array[i];
//array[i] = NULL;
}
delete[] array;
//array = NULL;
return 0;
}
Or should I create a vector
of vector
of pointers to Node
objects?
Or else should I allocate my objects on the stack?
(I'm using pointers, because in Java or C#, you have to always use the new
keyword when creating an object (however, I don't think all the objects are in the heap memory), and I read that there are more space available on the heap.)
An other reason I use pointers with the new
keyword, that I would like to create multiple pointers to the same object.
Should I create one object on stack, and just create pointers to that object?