Copying from one dynamically allocated array to another C ++

It seems like it should have a super-simple solution, but I just can't figure it out. I just create a modified array and try to copy all the original values, and then finally deleting the old array to free up 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 happens here is that resized[i] = orig[i] copies the values โ€‹โ€‹by reference, not by value, since printing orig after it has changed returns a bunch of values โ€‹โ€‹of unwanted information, unless I comment on delete [] orig . How can I make a deep copy from the original to resize, or is there some other problem I am facing? I do not want to use std :: vector.

+4
source share
3 answers

Remember that parameters in C ++ are passed by value. You assign a resized copy of the pointer that was passed to you, the pointer outside the function remains the same.

You should either use a double indirect (or double pointer), i.e. a pointer to a pointer to an 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 link to a 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 keep the size for any object and makes it clear that we are dealing with the size of the object.

+7
source

I highly recommend replacing arrays with std::vector<int> . This data structure will change as needed, and resizing has already been tested.

+3
source

orig must be a pointer to a pointer to assign it resized :

 int **orig; *orig = resized; 
+2
source

Source: https://habr.com/ru/post/1380272/


All Articles