How do I properly delete an array of doubles through a pointer after the pointer has been iterated?
I have created an array of doubles using the following code:
double *points = new double[(ii+1)*(jj+1)*(kk+1)*3];
I realize that in order to delete the array, all I have to do is:
delete[] points;
However; the array is created in a function (called create_points) that passes the address of the first element as follows:
return &points[0];
The code that calls this function then iterates through the address:
double *address = create_points(x_dim,y_dim,z_dim);
for(int k=0; k<x_dim+1; ++k)
for(int j=0; j<y_dim+1; ++j)
for(int i=0; i<z_dim+1; ++i) {
v[p_count].x = *address;
++address;
v[p_count].y = *address;
++address;
v[p_count].z = *add开发者_开发技巧ress;
++address;
++p_count;
}
Now my question is, how do I properly delete the array of doubles that address is used to access? Can I simply go delete[] address
, or do I have to do this some other way?
You cannot say delete[] address
, doing so is undefined behavior. You have to delete it through a pointer to the original base address of the array. So, if you're going to increment the pointer, you need to remember the original pointer (or recompute it):
double *base_address = create_points(...);
double *address = base_address;
// do stuff with address, increment it, etc.
delete [] base_address
You have to give the right address. It does not suffice that the address lies within the allocated region.
Why not keep a copy of the pointer before starting the iteration? &points[0] == points
It is only defined behavior to delete what you allocated, and that would be the address returned via create_points
.The best way would be to iterate over a temporary.
double *address = create_points(x_dim,y_dim,z_dim);
double *a = address;
for(int k=0; k<x_dim+1; ++k)
for(int j=0; j<y_dim+1; ++j)
for(int i=0; i<z_dim+1; ++i) {
v[p_count].x = *a;
++a;
v[p_count].y = *a;
++a;
v[p_count].z = *a;
++a;
++p_count;
}
delete[] address;
精彩评论