一个动态分配二维数组程序的特例

来源:互联网 发布:录入软件 编辑:程序博客网 时间:2024/05/17 04:38

通常,动态分配二维数组的原型为:

Code:
  1. T **dmalloc(int rows, int cols);   
  2. void dfree(T** p, int rows);  

写成模板后的代码:

Code:
  1. #include<iostream>   
  2. using namespace std;   
  3.   
  4. template<class T>   
  5.   
  6. T **dmalloc(int rows, int cols)   
  7. {   
  8.     int i;   
  9.     T **p = NULL;   
  10.     p = new T*[rows];   
  11.     for(i = 0; i < rows; i++)   
  12.     {   
  13.         p[i] = new T[cols];   
  14.     }   
  15.     return p;   
  16. }   
  17.   
  18. template<class T>   
  19. void dfree(T** p, int rows)   
  20. {   
  21.     for(int i = 0; i < rows; i++)   
  22.         delete[] p[i];   
  23.     delete[] p;   
  24.     p = NULL;   
  25. }   
  26.   
  27. int main()   
  28. {   
  29.     int **p = dmalloc<int>(10,20);   
  30.     p[0][2] = 10;   
  31.     cout<<p[0][2];   
  32.     dfree(p,10);   
  33.     return 0;   
  34. }  

但这里提供的原型是这样的:

Code:
  1. T** dmalloc(int rows, int cols);   
  2. void dfree(T** p);//只有一个参数,没有rows这个形参  

实现后的模板代码为:

Code:
  1. #include<iostream>   
  2. using namespace std;   
  3.   
  4. template<class T>   
  5. T** dmalloc(int rows, int cols)   
  6. {   
  7.     char *p = new char[rows*sizeof(char *) + sizeof(int)];   
  8.     int *p1 = (int *)(p);   
  9.     *p1 = rows;   
  10.     p1++;   
  11.     T **p3 = (T**)p1;   
  12.     for(int i = 0; i < rows; i++)   
  13.         p3[i] = new T[cols];       
  14.     return p3;   
  15. }   
  16.   
  17. template<class T>   
  18. void dfree(T** p)   
  19. {   
  20.     int *p1 = (int*)p;   
  21.     int rows = *--p1;   
  22. //  printf("%d/n",rows);   
  23.     T** p2 = (T**)++p1;   
  24.     for(int i = 0; i < rows; i++)   
  25.         delete[] p2[i];   
  26.     char *p3 = (char*)(--p2);   
  27.     delete[] p3;   
  28. }   
  29.   
  30. void main()   
  31. {   
  32.     int **p = dmalloc<int>(10,20);   
  33.     p[3][0] = 3;   
  34.     p[0][2] = 10;   
  35. //  p[100][100] = 12;   
  36. //  printf("%d",p[3][0]);   
  37.     dfree(p);   
  38. }   

总结:

通常我们把数组作为参数,要传递首地址和元素个数,但这里的函数原型没有元素个数,我们就要想一个办法将元素个数存储在数组中,当然可以给数组做一个结束标记,但这里的解决方法是将元素个数这个int值存储在数组首地址之前的4个字节中。

原创粉丝点击