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

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.