I am getting an error main.cpp…
Don't use the file name suffix .cpp
for C programs - .cpp
may cause gcc
to compile the source code for another language.
I need to reallocate both rows and columns.
Since you don't pass dimensions to your increase()
function, you apparently want it to increase the number of both rows and columns by 5. Since you used realloc(*arr, 5 * sizeof (int))
, you apparently overlooked that the size passed to realloc()
is not an increment, but rather the total size of the new memory space. Also, you should account for the possibility that the reallocation in increase()
fails, and allow it to return an error indication. The following example returns the new (maybe moved) pointer or NULL in case of failure. As a bonus, this increase()
function can also be used for the initial creation.
int row, col;
#include <malloc.h>
int **increase(int **arr)
{ // enlarge the "matrix" by 5 rows and 5 columns
int rownew = row+5, colnew = col+5;
arr = realloc(arr, rownew * sizeof *arr); // increase the rows
if (!arr) return NULL; // realloc error
do arr[row++] = NULL; while (row < rownew); // initialize new row pointers
for (rownew = 0; rownew < row; ++rownew)
{ // increase the columns in each row
int *newptr = realloc(arr[rownew], colnew * sizeof *newptr);
if (!newptr) return NULL; // realloc error
arr[rownew] = newptr;
}
col = colnew;
return arr;
}
main()
{
int **arr = increase(NULL); // create initial 5x5 "matrix"
int **newarr = increase(arr); // enlarge to new 10x10 "matrix"
if (newarr) arr = newarr;
else /* realloc error handling */;
}
Note that in something other than that toy example, we'd probably pass the dimensions as parameters rather than as globals.