delete[] - Pointers

I have a question. I have written a little program that uses pointers and does simple things with those. I have only a question about delete[] function.

If I have

1
2
3
4
5
6
7
8
	int* p1 = new int[10] {100, 101, 102, 103, 104, 105, 106, 107, 108, 109};   // Allocate and initialize with curly braces parentheses
	                                                                         // a new pointer.
	cout << endl;
	print_array10(cout, p1);

	delete[] p1;

	int* p1 = new int[11] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110 };


even if I delete[] pointed memory from free store, why compiler says that I multiple initialize the pointer? Once destroyed I am able to create, if I want, another one with the same name but different random address, don't I?

Thanks!
Last edited on
You are declaring the variable p1 twice in the same scope which is not allowed. If you remove int* from the last line it should compile without errors.
So even if I destroy before create it again saw that they are in the same scope compiler returns me an error right?
new[] creates an unnamed block of memory. Let's call that memory 'foo':

 
int* p1 = new int[10] {100, 101, 102, 103, 104, 105, 106, 107, 108, 109};


Here, 'foo' is the array of 10 integers.
'p1' is a local pointer which points to the first element in that array.

delete does not actually delete the pointer, it deletes what the pointer points to (in this case, 'foo'):
 
delete[] p1;


Here, 'foo' is deleted and no longer exists.
'p1' still exists as a local pointer. Only now it points to bad memory.

 
int* p1  // <-  this creates p1 AGAIN which will cause an error 


Remember that p1 still exists -- it's just 'foo' that doesn't exist any more. So if you want to have 'p1' point to a new buffer... let's say.... 'foo2':

1
2
3
4
// get rid of the int* declaration, and just reuse p1:
p1 = new int[11] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110 };

// this will create a new array 'foo2', and will make 'p1' point to the first element 
Thanks.. All clear now! :D
Topic archived. No new replies allowed.