I am trying to make a deep copy of a pointer to an array of integer, and am having trouble deciding what code is unnecessarily verbose and what is needed.
The pointer I am trying to copy is just a simple integer array.
int* vertexArray = new int[G->size()];
It contains the numbers 0 to size()-1 as its values. My first though was to make a new int* where equal to vertex array,
int* shortestTour = vertexArray
but I believe that will make the shortestTour change every time I permute the vertexArray. Is the only way to make a deep copy of this with a loop like this
for(int i=0; i<G->size(); i++){
shortestTour[i] = vertexArray[i];
}
and then to run that loop every time I find a tour/path shorter than the current shortest?
EDIT: This is for a simple, brute force implementation of the travelling salesman problem.
As you may have guessed, a deep copy is not copying the pointer (after all, a pointer is just an address that points to some memory location), but copying the memory that is being pointed by the pointer.
So, if you have
int* vertexArray = new int[G->size()];
a deep copy is
int* deepCopy = new int[G->size()];
for(size_t i = 0; i < G->size(); ++i)
deepCopy[i] = vertexArray[i]; // copy the allocated memory
Of course, there are smarter and faster ways of copying the memory, like
std::memcpy(deepCopy, vertexArray, sizeof(int)*G->size()); // should be faster
A shallow copy is just copying the pointer, not the memory,
int* shallowCopy = vertexArray;
Any modifications you'll make will be reflected by both shallowCopy
and vertexArray
pointers, as both now point to the same memory chunk.
You should think whether you need a deep copy or not. If you just want to share data around, you probably don't. If the data must be "local", then probably you do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With