日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组

發(fā)布時間:2024/4/17 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

?

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語言函數(shù)my2DAlloc用來給一個二維數(shù)組分配內存,并且讓我們盡可能的少調用malloc函數(shù)。一個二維數(shù)組實際是數(shù)組的數(shù)組,我們用指針來表示數(shù)組,用雙指針來表示二維數(shù)組。我們首先建立一個一維數(shù)組,對于每個位置,再建立一個一維數(shù)組,這樣我們就得到了一個二維數(shù)組,參見如下代碼:

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); }

?

其實我們還可以在連續(xù)的內存塊上來分配內存,例如對于一個5行6列的二維數(shù)組,我們可以在開頭的五個內存塊里存上每一行的起始地址,后面的五行數(shù)據(jù)是連續(xù)排列的,一行接著一行,參見代碼如下:

?

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;} };

?

這樣申請連續(xù)的一段內存空間的好處是只需要調用一次malloc就行,而且在釋放的時候也不需要特別的寫函數(shù)來free,好處還是蠻多的。

?

總結

以上是生活随笔為你收集整理的[CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。