I try to swap 2 dynamic allocated array that have different capacity. I try to use:
int *temp = arr1;
int arr1 = arr2;
int arr2 = temp;
However this approach doesn’t work. So I try different approach:
ItemType *temparr1 = new ItemType[other.capacity];
std::copy(setMember, setMember+capacity, temparr1);
ItemType *temparr2 = new ItemType[this->capacity];
std::copy(setMember, setMember+capacity, temparr2);
delete [] this->setMember;
delete [] other.setMember;
other.setMember = temparr1;
this->setMember = temparr2;
Unfortunately, this approach cast an error message :”Windows has triggered a breakpoint in Hw1.exe.
This may be due to a corruption of the heap, which indicates a bug in Hw1.exe or any of the DLLs it has loaded.”
any idea how can I swap dynamic allocated array? thx
You can’t swap the memory because it’s not the same size (assuming
other.capacityis different thanthis->capacity– if it was, you wouldn’t get the runtime error).Use
std::vectorinstead.If you just want to swap what the pointers point to:
or
Again, note that these won’t swap the actual memory, but the values of the pointers.
Observe the missing
intdeclarations which you initially had.