Sign in to follow this  
obi-wan shinobi

Dynamic memory allocation in c++

Recommended Posts

In dealing with pointers, I learned that dynamically allocating space for a 1D array goes like this:
int i;
cin >> i;
int *array1D = new int[i];
delete[] array1D;

Where 'i' is entered by the user. With 2D arrays, I think this is how the allocation would go:
int x,y;
int **array2D;
cin >> x;
cin >> y;
array2D = new int*[x];
for(int a=0;a<x;a++) {
*(array2D+a) = new int[b];
}
delete[] array2D;

As for 3D arrays, my best guess is to follow the previous example by adding a for loop:
int x,y,z;
int ***array3D;
cin >> x;
cin >> y;
cin >> z;
array3D = new int**[x];
for(int a=0;a<y;a++) {
*(array3D+a) = new int*[y];
for(int b=0;b<z;b++) {
**(array3D+b) = new int[z];
}
}
delete[] array3D;

Now I've noticed that I could write past the end of an array index whenever I want to without the program crashing, so that wouldn't be a reliable way to keep track of which dimension has how many elements. My questions are: 1) Would I have to write my own code to prevent writing past the end of an array if the compiler doesn't? 2) Why is it that when I write something like 'delete[][] array2D;', it's an error, but 'delete[] array2D;' isn't? Since array2D is 2-dimensional, shouldn't it require two pairs of square brackets?

Share this post


Link to post
Share on other sites
1) You will have to check the boundary of dynamically allocated arrays manually.
The compiler will not help you with this, so store the size of the array
somewhere or evenbetter yet - use std::vector.

2) Dynamic multi-dimensionl arrays are not supported by the new operator, so
delete [] array2d will create a memory leak since you only free the "row"
vectors, but not the manually allocated columns.


int x,y;
int **array2D;
cin >> x;
cin >> y;

// allocate
array2D = new int*[x];

for(int a = 0; a < x; ++a) {
array2D[a] = new int[y];
}

// de-allocate

for(int a = 0; a < x; ++a) {
delete array2D[a];
}

delete[] array2D;



Since this can get tedious with higher dimensionl arrays, you'd best use a 1D array and map the indices instead:


int x,y, width, height;
int *array2D;
cin >> width;
cin >> height;

// allocate
array2D = new int[width * height];

cin >> x;
cin >> y;

// access (x,y) -> watch for under- and overflows!
int value = array2D[y * width + x];

// de-allocate
delete[] array2D;



Again, std::vector makes things easier.

HTH,
Pat.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this