您的位置:首页 > 编程语言 > C语言/C++

【C++】用C编写一个my2DAlloc函数,可以分配二维数组。

2015-07-24 14:39 375 查看
用C编写一个my2DAlloc函数,可以分配二维数组。将malloc()的调用次数降到最少,并确保可以通过arr[i][j]访问该内存

二维数组就是数组的数组,首先想到,先创建一个一维的指针数组,每个指针指向一个一位数组。如下:

int** my2DAlloc(int rows, int cols) {
int** rowptr;
int i;
rowptr = (int**)malloc(rows * sizeof(int*));
for ( i = 0; i < rows; i++) {
rowptr[i] = (int*)malloc(cols * sizeof(int));
}
return rowptr;
}可以看到,malloc()调用的次数很多,而且释放这些内存时,要确保不仅释放掉第一次malloc后分配的内存,还要释放后续为每一行malloc分配的内存。
有没有其他办法呢?可以尝试一次性分配一大块连续的内存吗?那么索引怎么确定?

有的。

连续分配一大块内存,存放所有数据,再分配一小块内存存放每一行的首地址,根据行数和列数我们可以算出每一行是从哪个位置开始的

header代表指向每一行行首的指针的大小之和

int** my2Dalloc(int rows, int cols) {
header = rows * sizeof(int*);
int data = rows * cols * sizeof(int);
int** rowptr = (int**)malloc(header + data);
if(row == NULL) return NULL;
int* buf = (int*)(rowptr + rows);
for(int i = 0; i < rows; i++) {
rowptr[i] = buf + i * cols;
}
return rowptr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: