Free memory of array that is pointed to

Hi there,

sorry for posting this quite redundant question, but I think I really didn't get the point and I wonder if this problem really equals the "how to delete an array of pointers" one.

-BTW, I want to try this with traditional arrays, not the boost::vector class--

So here comes my use case, and then the problem. I want to estimate an array of values. In each iteration, a new estimation is made and a persistent pointer is moved to the address of the new estimation. Of course, I want to free the prior estimation from memory before the new one is assigned to the pointer.

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
float **pp = new float[N];
while(COND){

   //Do some calculations with pp[i]

   float *p_New = new float[N];
   //Do some calculations with p_New[i]

   //Replace old array associated with pp with the new one
   delete[] *pp;
   pp = p_New;

}


Problem:
1) Is this the best way to realize this use-case (a persistent pointer referencing a new array after each iteration)?
2) Why does delete[] *pp not work? Dereferencing pp should give me the address of the array it is pointing to, right?

Any answers are highly appreciated. Thanks!

Best,
Chris
*pp was never allocated using new, so you cannot delete it.

new float[N] gives you a pointer to a float, which is the start of an array.

float **pp = new float[N]; should not compile, as you're trying to assign a pointer to a float to a pointer-to-a-pointer-to-a-float.

I think you meant this:
float* pp = new float[N];

Dereferencing pp should give me the address of the array it is pointing to, right?
Wrong. Dereferencing a pointer does not give you the address it is pointing to. It gives you the thing being pointed at. The pointer already is the address of the thing being pointed at. Please read up on pointers. Here is my standard "what are pointers" spiel: http://www.cplusplus.com/articles/EN3hAqkS/

not the boost::vector class
It's been std::vector for as long as I can remember. Vectors are part of C++ - you don't need additional libraries such as Boost to use them.
Last edited on
Topic archived. No new replies allowed.