现在的位置: 首页 > 综合 > 正文

二维数组动态生成与释放(c/c++)

2013年11月30日 ⁄ 综合 ⁄ 共 903字 ⁄ 字号 评论关闭
熟悉下new,delete, malloc, free。
不过好像混用也可以
  1. #include <stdlib.h>
  2. #include <assert.h>
  3. #include <iostream>
  4. using namespace std;
  5. template<class T>
  6. bool Make2DArray(T** &x, int rows, int cols)
  7. {
  8.     try{
  9.         x = new T*[rows];
  10.         for (int i=0; i<rows; i++)
  11.             x[i] = new T[cols];
  12.         return true;
  13.     }catch(...)
  14.     {
  15.         cerr<<"new error!"<<endl;
  16.         return false;
  17.     }
  18. }
  19. template<class T>
  20. void Delete2DArray(T **&x, int rows)
  21. {
  22.     for (int i=0; i<rows; i++)
  23.     {
  24.         delete[] x[i];
  25.     }
  26.     delete[] x; 
  27.     x = NULL;
  28. }
  29. bool Make(char **&x, int rows, int cols)
  30. {
  31.     int i;
  32.     x = (char **)malloc(sizeof(char *)*rows);
  33.     assert(x != NULL);
  34.     for (i=0; i<cols; i++)
  35.     {
  36.         x[i] = (char *)malloc(sizeof(char)*cols);
  37.         assert(x[i]);
  38.     }
  39.     return true;
  40. }
  41. void free2D(char **&p, int rows)
  42. {
  43.     int i;
  44.     for (i=0; i<rows; i++)
  45.     {
  46.         free(p[i]);
  47.         p[i] = NULL;
  48.     }
  49.     free(p);
  50.     p = NULL;
  51. }

抱歉!评论已关闭.