13.10 Write a my2dalloc function in C to allocate a two-dimensional array. Minimize the number of calls to the malloc function and ensure that the memory is accessible through arr[i][j].
Solution:
The simplest way to do this is to first open an array to store pointers to each row, and then allocate space dynamically for each row. This is a very common method of dynamically applying a two-dimensional array space:
int* * MY2DALLOC (intint cols) {int **arr = (int* *) malloc ( rows*sizeof(int*)); for (int i=0; i<rows; + +i ) = (int*) malloc (cols*sizeof(int)); return arr;}
The above method uses the (rows+1) times the malloc,malloc use too much can affect the program's running efficiency, then there is no way to reduce the use of malloc.
While the thing we do is dynamically apply for two-dimensional array space, the space for these applications is essentially one-dimensional, except that some space stores the address, while some space stores the data. For example, the method above applies a one-dimensional array of rows in length, which holds the pointer (int*) and points to the address of each row. Then we applied for rows*cols size space, which is the integer data (int). That being the case, we can apply so much space at once and then store the address in the space where the data is stored and the data is OK.
We need to store the address that points to each row, size:
int sizeof (int*);
You also need to store Rows*cols integer data in the following sizes:
int sizeof (int);
We apply these spaces at once:
int **arr = (int* *) malloc (header + data);
Because the size of the front rows * sizeof (int*) is a pointer, the ARR type is int**. When you cross rows of cells, the data behind the integer is stored, so you need to convert the type to int*:
int *buf = (int*) (arr + rows);
Finally, starting with the address pointed to by BUF, each cols unit consists of one row, and the address of the beginning is stored in the appropriate location in arr.
for (int i=0; i<rows; + +i ) = buf + i * cols;
The code is as follows:
int* * MY2DALLOC1 (intRowsintcols) { intHeader = rows *sizeof(int*); intdata = rows * cols *sizeof(int); int**arr = (int* *) malloc (header +data); int*buf = (int*) (arr +rows); for(intI=0; i<rows; ++i) arr[i]= buf + i *cols; returnarr;}
In this way, we use malloc once to dynamically request a two-dimensional array space, and can be accessed using the Arr[i][j] array element.
Careercup-c and C + + 13.10