It’s been about 2 months since I started to learn c++ and I’m not quite sure about I’m doing wrong for my project. I have a dynamically allocated array with an initial size and after I want to change the size of it. The thing I wonder is why the following code is wrong
int *firstPtr = new int [4];
for (int i = 0; i < 4; i++) {
firstPtr[i] = i;
}
int *tempPtr = new int[5];
for (int i = 0; i < 4; i++) {
tempPtr[i] = firstPtr[i];
}
tempPtr[4] = 4;
// firstPtr = new int[5];
firstPtr = tempPtr;
delete tempPtr;
for (int i = 0; i < 5; i++) {
cout << firstPtr[i] << endl;
}
because the output is:
10757752
10753936
2
3
4
PS: I can’t use realloc/malloc etc for this since the project is just about pointers. How can I correct this without them.
first Ptr now points to the same memory as tempPtr.
You are now deleting that memory, the same memory both firstPtr and tempPtr are pointing to.
You are accessing deleted memory, the values printed can be anything.
To get what I’m assuming you want, you need to remove the line
or delete the memory after the for:
Note that in the second case you will get a memory leak, since the memory initially pointed to by
firstPtris no longer accessible.A complete working and correct code would be as follows:
Some ASCII art:
So now, in memory, you have:
Your next line:
does this:
So now, tempPtr points to delete memory. Hope this clears things up.