Assuming you declared array
as
int **array;
and allocated as
array = malloc( sizeof *array * ROWS );
if ( array )
{
for ( size_t i = 0; i < ROWS; i++ )
array[i] = malloc( sizeof *array[i] * COLS );
}
The structure you wind up with looks something like:
+---+ +---+ +---+
array: | | -----> | | array[0] ------> | | array[0][0]
+---+ +---+ +---+
... | | array[1] ---+ | | array[0][1]
+---+ | +---+
... | | | array[0][2]
| +---+
| ...
|
| +---+
+--> | | array[1][0]
+---+
| | array[1][1]
+---+
| | array[1][2]
+---+
...
If you want to increase the number of rows in the array but leave the column sizes the same, you'd do something like
int **tmp = realloc( array, sizeof *array * (ROWS + add_rows) );
if ( tmp )
{
array = tmp;
for ( size_t i = 0; i < add_rows; i++ )
{
array[ROWS + i] = malloc( sizeof *array[ROWS + i] * COLS );
}
}
If you want to leave the number of rows the same but increase the number of columns in each row, you would do something like
for ( size_t i = 0; i < ROWS; i++ )
{
int *tmp = realloc( array[i], sizeof *array[i] * (COLS + add_cols) );
if ( tmp )
{
array[i] = tmp;
}
}
If you want to reduce the number of rows in the array, you will need to free the affected rows first:
for ( size_t i = 1; i <= del_rows; i++ )
free( array[ROWS - i] );
int *tmp = realloc( array, ROWS - del_rows );
if ( tmp )
array = tmp;
If you want to reduce the number of columns:
for ( size_t i = 0; i < ROWS: i++ )
{
int *tmp = realloc( array[i], sizeof *array[i] * (COLS - del_cols) );
if ( tmp )
array[i] = tmp;
}
From there, you should be able to figure out any combinations you need. I strongly recommend doing only one dimension at a time (that is, if you want to increase the number of rows and columns, do the rows first, then do the columns).
You always want to assign the result of realloc
to a temporary variable; if realloc
cannot satisfy the request, it will return NULL
, and if you assign it back to the original variable, you will lose your only reference to the memory that was previously allocated, leading to a memory leak.