- You should reduce the number of columsn, not rows.
- Not
mat1
butmat1->array
should be reallocated. - Not
nrow
andncol
(not updated) butmat1->nrows
andmat1->ncols
(updated) should be used for the new size. - The elements are
size_t
, so allocating forint
mayn’t be enough. Using the variable for calculating size is safe.
In the other words, this part
mat1->nrows = mat1->nrows - 1;
mat1->array = (size_t *) realloc(mat1, nrow * ncol * sizeof(int));
should be
mat1->ncols = mat1->ncols - 1;
mat1->array = (size_t *) realloc(mat1->array, mat1->nrows * mat1->ncols * sizeof(*mat1->array));
and the part (the 4th line of main()
body)
mat1->array = (size_t *) malloc(mat1->nrows * mat1->ncols * sizeof(int));
should be
mat1->array = (size_t *) malloc(mat1->nrows * mat1->ncols * sizeof(*mat1->array));
Note that this simple reallocation works only because the matrix has only one row. For matrice having multiple rows, you should move (using memmove
or manually) second and later rows to match the new number of columns.
2
solved How to shrink at runtime a struct matrix (using realloc() for example)