[CareerCup] 13.10 Allocate a 2D Array 分配一個二維陣列

Grandyang發表於2015-11-04

 

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,好處還是蠻多的。

 

相關文章