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 = *address;
++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):