C++ Program to Allocate Memory using new[ ] and delete[ ]
Posted by Superadmin on August 10 2022 08:19:17

C++ Program to Allocate Memory using new[ ] and delete[ ]

 

 

This C++ program illustrates memory allocation and de-allocation using new and delete keywords. The space for one-dimensional and two-dimensional arrays can be allocated and de-allocated using these keywords. In case of two-dimensional array, the array first allocated is that for holding pointers to further one-dimensional arrays.

 

Here is the source code of the C++ program illustrates memory allocation and de-allocation using new and delete keywords. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Allocate Memory using new[] and delete[]
  3.  */
  4. #include <iostream>
  5.  
  6. int main()
  7. {
  8.     int size;
  9.     int sizex, sizey;
  10.  
  11.     std::cout << "Enter the size of one-dimensional array ";
  12.     std::cin >> size;
  13.     // One-dimensional array
  14.     int *arr = new int[size];
  15.     for (int i = 0; i < size; i++)
  16.         std::cin >> arr[i];
  17.     delete[] arr;
  18.     // Two-dimensional array
  19.     std::cout << "Enter the size of two-dimensional array ";
  20.     std::cin >> sizex >> sizey;
  21.     int ** arr_2d = new int*[sizex];
  22.     for(int i = 0; i < sizex; i++)
  23.         arr_2d[i] = new int[sizey];
  24.     for (int i = 0; i < sizex; i++)
  25.     {
  26.         for(int j = 0; j < sizey; j++)
  27.             std::cin >> arr_2d[i][j];
  28.     }
  29.     // Deleting array completely
  30.     for(int i = 0;i < sizex; i++)    
  31.         delete[] arr_2d[i];
  32. }

 

$ a.out
Enter the size of one-dimensional array 2
1 3
Enter the size of two-dimensional array 2 2
1 2
3 4