Skip to content

Instantly share code, notes, and snippets.

@ILoveBacteria
Created December 31, 2022 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ILoveBacteria/748705c7be175a971c563ba6ecb66dc2 to your computer and use it in GitHub Desktop.
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)
#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