13.10 Write a function in C called My2dalloc which allocates a two-dimensional array. Minimize the number of calls to malloc and make sure that the memory are accessible by the notation arr[i][j].
This problem lets us write a C-language function My2dalloc to allocate memory for a two-dimensional array, and let us call the malloc function as little as possible. A two-dimensional array is actually an array of arrays, we use pointers to represent arrays, and two-dimensional arrays with double pointers. We first create a one-dimensional array, for each location, and then create a one-dimensional array, so that we have a two-dimensional array, see the following code:
int * * MY2DALLOC (int rows, int cols) { int **rowptr = (int * *) malloc (rows * sizeof ( Span style= "color: #0000ff;" >int * for (int i = 0 ; i < rows; ++i) {Rowptr[i] = (int *) malloc (cols * sizeof (int )); return rowptr;}
About freeing up memory, we can't just release rowptr, we want to make sure that the memory in each cell is also freed, see the following code:
void my2ddealloc (intint rows) { for (int0; i < Rows + +i) {free(rowptr[i]) ; } Free (rowptr);}
In fact, we can also allocate memory on a contiguous block of memory, for example, a two-dimensional array of 5 rows and 6 columns, we can be in the beginning of the five memory block to save the start of each row, the following five rows of data is continuous arrangement, one line after another, see the code is as follows:
classSolution { Public: int* * MY2DALLOC (intRowsintcols) { intHeader = rows *sizeof(int*); intdata = rows * cols *sizeof(int*); int**rowptr = (int**)malloc(Header +data); if(rowptr = = NULL)returnNULL; int*buf = (int*) (Rowptr +rows); for(inti =0; i < rows; ++i) {Rowptr[i]= buf + i *cols; } returnrowptr; }};
The benefit of applying a contiguous memory space is that you only need to call malloc once, and you don't need a special write function to free at the time of release, and the benefits are pretty much.
[Careercup] 13.10 Allocate a 2D array assigns a two-dimensional