Using multidimensional arrays, this can be done with pointers or without pointers to arrays of variable length. Since you probably do not want to allocate additional memory, this will be done locally.
First select an array of size 20 by 10:
int ( *array )[10] = malloc( sizeof(int ) * 20 * 10 ); for( size_t i = 0 ; i < 20 ; i++ ) for( size_t j = 0 ; j < 10 ; j++ ) array[i][j] = i * 100 + j;
If you want to change the number of rows, the elements should not be moved, only realloc is needed. Changing the number of rows to 15 is trivial:
array = realloc( array , sizeof( int ) * 15 * 10 );
If you want to change the number of columns, the elements must be moved. Since we do not need to copy the first column, copying starts from the second. The memmove function is used to avoid overlapping memory, which cannot happen in this case, but could be if the number of new columns is greater. It also avoids problems with an alias. Please note that this code is determined only because we use allocated memory. Let me change the number of columns by 3:
int (*newarray)[3] = ( int(*)[3] )array; for( size_t j = 1 ; j < 15 ; j++ ) memmove( newarray[j] , array[j] , sizeof( int ) * 3 ); newarray = realloc( array , sizeof( int ) * 15 * 3 );
Working example: https://ideone.com/JMdJO0
If the number of new columns is greater than the old, then you first need to reallocate the memory (just get more space), and then the columns will be copied, instead, starting from the last column.
source share