Jason Lutz Jason Lutz - 1 year ago 127
C++ Question

How to Reallocate/Resize a 3d array to fit into a new size c++

So for a project I have i need to create a function to 'Resize' the first dimension of a dynamically allocated 3d array of shorts, the function cant alter the original data and must only alter the first dimension of the array.

3darray[alter this][stays the same][stays the same]

The variables passed into the function are the pointer that points to the 3d array, the old size, and the new size.

Ive tried this:

void reallocShort3d(short ***&ptr, size_t oldSize, size_t newSize)
short *** temp;

temp = (short***) realloc(ptr,(newSize - oldSize) * sizeof(ptr));

ptr = temp;

but it does not seem to be working, any idea on where i went wrong and possible solutions?


EDIT: I realise that I can't use
now as th 3d array was created with
, we are only given the old and new sizes of the first dimension and the array itself, we are not allowed to use vectors:

* @brief reallocates/resizes a 3D array of shorts to fit into a new size.
* Size here refers to the first dimension. i.e. ptr[size][row][col].
* @note after the function executed, the original data in the array must
* not be altered in any way. That is to say, only the first dimension of
* ptr may be altered.
* @NOTE! this function must work in general
* @param ptr is the pointer that refers to the 3D array to be resized.
* @param oldSize is the current total number of elements in the first
* dimension of ptr. e.g. ptr[this amount here][row][col]
* @param newSize is the new size that ptr will have after the function
* has been executed. ptr[the new amount here][row][col]


Heres the code used to allocate the 3d array:

ptr = new short**[2];

for (int i = 0; i < 2; i++)
ptr[i] = new short*[12];
for (int j = 0; j < 12; ++j)
ptr[i][j] = new short[numDaysinMonth(j)];

Answer Source

Given the way OP's code allocates the memory, a simple way to resize it is:

short ***tmp;

// in OP's code rows = 12 while the inner dimension is the number of days in a month
// so we can use cols = 31

tmp = new short**[newSize];
// copy the old data
for ( size_t i = 0; i < oldSize; ++i ) {
    tmp[i] = ptr[i];
// allocate memory for the new data
for ( size_t i = oldSize; i < newSize; ++i ) {
    tmp[i] = new short*[rows];
    for ( size_t j = 0; j < rows; ++j ) {
        tmp[i][j] = new short[cols];
delete[] ptr;
ptr = tmp;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download