Copying from One Dynamically Allocated Array to Another C++
Solution 1
Remember, parameters in C++ are passed by value. You are assigning resized
to a copy of the pointer that was passed to you, the pointer outside the function remains the same.
You should either use a double indirection (or a "double pointer", i.e. a pointer to a pointer to int
):
void ResizeArray(int **orig, int size) {
int *resized = new int[size * 2];
for (int i = 0; i < size; i ++)
resized[i] = (*orig)[i];
delete [] *orig;
*orig = resized;
}
or a reference to the pointer:
void ResizeArray(int *&orig, int size) {
int *resized = new int[size * 2];
for (int i = 0; i < size; i ++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
}
By the way, for array sizes you should use the type std::size_t
from <cstddef>
- it is guaranteed to hold the size for any object and makes clear that we are dealing with the size of an object.
Solution 2
I highly suggest replacing the arrays with std::vector<int>
. This data structure will resize as needed and the resizing has already been tested.
Solution 3
orig
must be a pointer to a pointer to assign it to resized
:
int **orig;
*orig = resized;
Rahul Gupta-Iwasaki
Updated on July 09, 2022Comments
-
Rahul Gupta-Iwasaki almost 2 years
This seems like it should have a super easy solution, but I just can't figure it out. I am simply creating a resized array and trying to copy all the original values over, and then finally deleting the old array to free the memory.
void ResizeArray(int *orig, int size) { int *resized = new int[size * 2]; for (int i = 0; i < size; i ++) resized[i] = orig[i]; delete [] orig; orig = resized; }
What seems to be happening here is that
resized[i] = orig[i]
is copying values by reference rather than value, as printing orig after it gets resized returns a bunch of junk values unless I comment outdelete [] orig
. How can I make a deep copy from orig to resized, or is there some other problem that I am facing? I do not want to use std::vector. -
André Caron over 12 years+1 The other option is to return the new array using... the return value.
-
Matteo Italia over 12 years@AndréCaron: that's an option too, but I think that these forms suit better the indented use.
-
Michael Price over 12 yearsAs a point of clarification, by "double pointer" the respondent means "double indirection". When I first read it, I was confused why he wanted to substitute
double *
forint *
. -
Markus over 2 yearsWhile
vectors
in general are something interesting, there also exist a variety of reason against them. Thus, your answer is opinion-based and rather a comment than an actual answer to OP's problem. -
Thomas Matthews over 2 years@Markus: One could say the same about arrays. There also exists a variety of reasons against them, thus the OP's issue is opinion based and should be closed (and maybe deleted).