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

2014-04-25 20:47

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

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

代码:

 1 // 13.10 Write a function in C called my2DAlloc, which allocates space for 2d array. Try to minimize the number of mallocs and frees.

 2 #include <cstdio>

 3 #include <cstdlib>

 4 using namespace std;

 5 

 6 int **my2DAlloc(int row, int col)

 7 {

 8     if (row < 1 || col < 1) {

 9         return nullptr;

10     }

11 

12     int i;

13     int **a;

14     

15     a = (int **)malloc(row *  sizeof(int *));

16     a[0] = (int *)malloc(row * col * sizeof(int));

17     for (i = 1; i < row; ++i) {

18         a[i] = a[0] + i * col;

19     }

20 

21     return a;

22 }

23 

24 void my2DFree(int **ptr)

25 {

26     if (ptr == nullptr) {

27         return;

28     }

29     free(ptr[0]);

30     free(ptr);

31 }

32 

33 int main()

34 {

35     int row, col;

36     

37     scanf("%d%d", &row, &col);

38     int **a = my2DAlloc(row, col);

39     

40     int i, j;

41     

42     for (i = 0; i < row; ++i) {

43         for (j = 0; j < col; ++j) {

44             scanf("%d", &a[i][j]);

45         }

46     }

47     

48     for (i = 0; i < row; ++i) {

49         for (j = 0; j < col; ++j) {

50             printf("%d ", a[i][j]);

51         }

52         printf("\n");

53     }

54     

55     my2DFree(a);

56     

57     return 0;

58 }

 

你可能感兴趣的:(interview)