Reputation: 43
can you help me change the size of dynamic allocated 2D array. I need function witch change current array size for required size. I send my code for example. Thanks
int main()
{
//create array col x row
int **array = new int*[col];
for (int i = 0; i < col; i++)
{
array [i] = new int[row];
}
//add numbers to array
for (int i = 0; i < col; i++)
{
for (int j = 0; j < row; j++)
{
pole[i][j] = i*j;
}
}
/*
call function for change size of matrix ...
for example row to rov+5 and col to col+1 without loss of data
*/
//free memory
for (int i = 0; i < col; i++)
{
delete[] pole[i];
}
delete pole;
}
void resize(int ** & arr)
{
//code
}
Upvotes: 0
Views: 4892
Reputation: 76464
I would create a matrix having the needed size, the correct number of rows and the correct number of columns, copy the content of the old matrix and do whatever is needed to do with the new rows and new columns and then deallocate the old matrix.
Upvotes: 0
Reputation: 144
This is untested but will hopefully give you some ideas;
void create(int ** & arr)
{
//create array col x row
arr = malloc(col * sizeof(int*));
for (int i = 0; i < col; i++)
{
arr [i] = malloc(row * sizeof(int));
}
}
void destroy(int ** & arr)
{
for (int i = 0; i < col; i++)
{
free(arr [i]);
}
free(arr);
}
void resize(int ** & arr,int new_col,int new_row)
{
if (new_col == col)
{
if (new_row == row)
return;
for (int i = 0; i < col; i++)
{
arr [i] = realloc(arr [i],new_row * sizeof(int));
}
}
else if (new_col > col)
{
arr = realloc(arr,new_col * sizeof(int*));
if (new_row != row)
{
for (int i = 0; i < col; i++)
{
arr [i] = realloc(arr [i],new_row * sizeof(int));
}
}
for (int i = col; i < new_col; i++)
{
arr [i] = malloc(arr [i],new_row * sizeof(int));
}
}
else
{
if (new_row != row)
{
for (int i = 0; i < new_col; i++)
{
arr [i] = realloc(arr [i],new_row * sizeof(int));
}
}
for (int i = new_col; i < col; i++)
{
free(arr [i]);
}
arr = realloc(arr,new_col * sizeof(int*));
}
col = new_col;
row = new_row;
}
Upvotes: 0
Reputation: 114
I am not sure what do you want to accomplish here. Probably the easiest way is to copy the old matrix into a larger one, before deleting it. If you want to really reallocate the memory, and avoid more complex structures that c++ provides, you could use #include<cstdlib>
,and realloc()
all needed rows and columns. But that is not considered c++ style.
More info: http://www.cplusplus.com/reference/cstdlib/realloc/
Upvotes: 1