《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++的区别了。
代码:
题目:分配一个二维数组,尽量减少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; }
相关文章推荐
- 《Cracking the Coding Interview》——第13章:C和C++——题目5
- 《Cracking the Coding Interview》——第13章:C和C++——题目6
- 《Cracking the Coding Interview》——第13章:C和C++——题目7
- 《Cracking the Coding Interview》——第13章:C和C++——题目1
- 《Cracking the Coding Interview》——第13章:C和C++——题目8
- 《Cracking the Coding Interview》——第13章:C和C++——题目9
- 《Cracking the Coding Interview》——第13章:C和C++——题目2
- 《Cracking the Coding Interview》——第13章:C和C++——题目3
- 《Cracking the Coding Interview》——第13章:C和C++——题目4
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目10
- 《Cracking the Coding Interview》——第17章:普通题——题目10
- 《Cracking the Coding Interview》——第18章:难题——题目10
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目10
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目3
- 《Cracking the Coding Interview》——第5章:位操作——题目1
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目5
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目9
- 《Cracking the Coding Interview》——第14章:Java——题目3
- 《Cracking the Coding Interview》——第18章:难题——题目2
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目4