[CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组
生活随笔
收集整理的這篇文章主要介紹了
[CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
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 is accessible by the notation arr[i][j].
?
這道題讓我們寫個C語言函數my2DAlloc用來給一個二維數組分配內存,并且讓我們盡可能的少調用malloc函數。一個二維數組實際是數組的數組,我們用指針來表示數組,用雙指針來表示二維數組。我們首先建立一個一維數組,對于每個位置,再建立一個一維數組,這樣我們就得到了一個二維數組,參見如下代碼:
int** my2DAlloc(int rows, int cols) {int **rowptr = (int**)malloc(rows * sizeof(int*));for (int i = 0; i < rows; ++i) {rowptr[i] = (int*)malloc(cols * sizeof(int));}return rowptr; }?
關于釋放內存,我們不能僅僅釋放rowptr,我們要確保每個cell中的內存也被釋放了,參見如下代碼:
void my2DDealloc(int **rowptr, int rows) {for (int i = 0; i < rows; ++i) {free(rowptr[i]);}free(rowptr); }?
其實我們還可以在連續的內存塊上來分配內存,例如對于一個5行6列的二維數組,我們可以在開頭的五個內存塊里存上每一行的起始地址,后面的五行數據是連續排列的,一行接著一行,參見代碼如下:
?
class Solution { public:int** my2DAlloc(int rows, int cols) {int header = rows * sizeof(int*);int data = rows * cols * sizeof(int*);int **rowptr = (int**)malloc(header + data);if (rowptr == NULL) return NULL;int *buf = (int*)(rowptr + rows);for (int i = 0; i < rows; ++i) {rowptr[i] = buf + i * cols;}return rowptr;} };?
這樣申請連續的一段內存空間的好處是只需要調用一次malloc就行,而且在釋放的時候也不需要特別的寫函數來free,好處還是蠻多的。
?
總結
以上是生活随笔為你收集整理的[CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WIN10系统下sqlmap没有颜色和n
- 下一篇: Centos 开放端口