In C, I would have done it using realloc
.
In C++, one would normally consider using the STL vector
class.
But how do I properly resize an array in C++ without using any of the above solutions?
In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
Suggest Edits. In addition to resizing images using hard coded dimensions, you can use Image and Video Manager to dynamically resize images based on published dimensions.
There is no good equivalent of realloc
in C++. You'll need to manually duplicate the array and copy the old elements over. Fortunately, thanks to the std::copy
function in <algorithm>
, this isn't too bad:
size_t k = /* ... */
T* buffer = /* .. get old buffer of size k. .. */
T* newBuffer = new T[newSize]; // Assume newSize >= k
std::copy(buffer, buffer + k, newBuffer);
delete [] buffer;
buffer = newBuffer;
Hope this helps!
EDIT: Reordered the last two lines! Whoops!
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