Created
December 31, 2022 19:49
-
-
Save ILoveBacteria/748705c7be175a971c563ba6ecb66dc2 to your computer and use it in GitHub Desktop.
How to change the size of dynamic array in c++(like realloc in c)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define MIN(a, b) a < b ? a : b | |
void changeSize(int* &arr, int &size, int newSize) { | |
// Allocate a new array | |
int* newArray = new int[newSize]; | |
// Copy all elements to the new array | |
for(int i = 0; i < MIN(size, newSize); ++i) { | |
newArray[i] = arr[i]; | |
} | |
// Free and assign the new Array | |
delete[] arr; | |
arr = newArray; | |
size = newSize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment