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

《Cracking the Coding Interview》——第13章:C和C++——题目10

2014-04-25 21:00 555 查看
2014-04-25 20:47

题目:分配一个二维数组,尽量减少malloc和free的使用次数,要求能用a[i][j]的方式访问数据。

解法:有篇文章讲了六种new delete二维数组的方式,其中最后一种灰常高效。链接在此,解法六是巧妙的,不过里面的说法不对,而且还不标明转载原地址,可见这些技术网站的小编既不懂编程,也不尊重知识产权。没准这篇文章已经转载了无数次了。用这种方法创建和释放一个N维数组,只需要new和delete N次。我说的是N维,不是说长度。至于malloc和new的区别,就是C和C++的区别了。

代码:

// 13.10 Write a function in C called my2DAlloc, which allocates space for 2d array. Try to minimize the number of mallocs and frees.
#include <cstdio>
#include <cstdlib>
using namespace std;

int **my2DAlloc(int row, int col)
{
if (row < 1 || col < 1) {
return nullptr;
}

int i;
int **a;

a = (int **)malloc(row *  sizeof(int *));
a[0] = (int *)malloc(row * col * sizeof(int));
for (i = 1; i < row; ++i) {
a[i] = a[0] + i * col;
}

return a;
}

void my2DFree(int **ptr)
{
if (ptr == nullptr) {
return;
}
free(ptr[0]);
free(ptr);
}

int main()
{
int row, col;

scanf("%d%d", &row, &col);
int **a = my2DAlloc(row, col);

int i, j;

for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
scanf("%d", &a[i][j]);
}
}

for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
printf("%d ", a[i][j]);
}
printf("\n");
}

my2DFree(a);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐