fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template <typename T>
  6. T** create2DArray(unsigned nrows, unsigned ncols)
  7. {
  8. T** ptr = new T*[nrows]; // allocate pointers
  9. T* pool = new T[nrows*ncols]; // allocate pool
  10. for (unsigned i = 0; i < nrows; ++i, pool += ncols )
  11. ptr[i] = pool;
  12. return ptr;
  13. }
  14.  
  15. template <typename T>
  16. void delete2DArray(T** arr)
  17. {
  18. delete [] arr[0]; // remove the pool
  19. delete [] arr; // remove the pointers
  20. }
  21.  
  22. int main(){
  23.  
  24. int rows = 6;
  25. int columns = 3;
  26.  
  27. // allocate from the stack.
  28. double q[rows][columns];
  29.  
  30. // allocate from the heap.
  31. double ** a = create2DArray<double>(rows, columns);
  32.  
  33. // populate the arrays.
  34. for(int i = 0; i < rows; ++i){
  35. for(int j = 0; j < columns; ++j){
  36. a[i][j] = columns*i+j;
  37. q[i][j] = columns*i+j;
  38. }
  39. }
  40.  
  41. cout << "*****************" << endl;
  42. cout << "Array indexing method." << endl;
  43. cout << "*****************" << endl;
  44.  
  45. // print the heap allocated array using array indexing.
  46. for(int i = 0; i < rows; ++i){
  47. for(int j = 0; j < columns; ++j){
  48. cout << a[i][j] << '\t';
  49. }
  50. cout << endl;
  51. }
  52.  
  53. cout << "*****************" << endl;
  54.  
  55. // print the stack allocated array using array indexing.
  56. for(int i = 0; i < rows; ++i){
  57. for(int j = 0; j < columns; ++j){
  58. cout << q[i][j] << '\t';
  59. }
  60. cout << endl;
  61. }
  62.  
  63. cout << "*****************" << endl;
  64. cout << "Pointer dereferencing method." << endl;
  65. cout << "*****************" << endl;
  66.  
  67. // print the heap allocated array.
  68. for(int i = 0; i < rows; ++i){
  69. for(int j = 0; j < columns; ++j){
  70. cout << *(&a[0][0] + columns*i + j) << '\t';
  71. }
  72. cout << endl;
  73. }
  74.  
  75. cout << "*****************" << endl;
  76.  
  77. // print the stack allocated array.
  78. for(int i = 0; i < rows; ++i){
  79. for(int j = 0; j < columns; ++j){
  80. cout << *(&q[0][0] + columns*i + j) << '\t';
  81. }
  82. cout << endl;
  83. }
  84. cout << "*****************" << endl;
  85.  
  86. // release the memory allocated to the heap.
  87. delete2DArray<double>(a);
  88.  
  89. return 0;
  90. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
*****************
Array indexing method.
*****************
0	1	2	
3	4	5	
6	7	8	
9	10	11	
12	13	14	
15	16	17	
*****************
0	1	2	
3	4	5	
6	7	8	
9	10	11	
12	13	14	
15	16	17	
*****************
Pointer dereferencing method.
*****************
0	1	2	
3	4	5	
6	7	8	
9	10	11	
12	13	14	
15	16	17	
*****************
0	1	2	
3	4	5	
6	7	8	
9	10	11	
12	13	14	
15	16	17	
*****************