Advertisement
thecplusplusguy

2D dynamic array in C++

Sep 13th, 2012
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. //http://www.youtube.com/user/thecplusplusguy
  2. #include <iostream>
  3.  
  4. int main()
  5. {
  6.     //create a 2D dynamic array, a 2D dynamic array is an array of array (3D is an array of array of array...)
  7.     int rows=5;
  8.     int cols=10;
  9.     int **array=new int*[rows];
  10.     for(int i=0;i<rows;i++)
  11.         array[i]=new int[cols];
  12.    
  13.     //access a 2D dynamic array
  14.     for(int i=0;i<rows;i++)
  15.         for(int j=0;j<cols;j++)
  16.             array[i][j]=i+j;
  17.  
  18.     //write out a 2D dynamic array
  19.     for(int i=0;i<rows;i++)
  20.     {
  21.         for(int j=0;j<cols;j++)
  22.             std::cout << array[i][j] << ' ';
  23.         std::cout << std::endl;
  24.     }
  25.    
  26.     //delete a 2D dynamic array
  27.     for(int i=0;i<rows;i++)
  28.         delete[] array[i];
  29.     delete[] array;
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement