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.
/*
* C++ Program to Allocate Memory using new[] and delete[]
*/
#include <iostream>
int main()
{
int size;
int sizex, sizey;
std::cout << "Enter the size of one-dimensional array ";
std::cin >> size;
// One-dimensional array
int *arr = new int[size];
for (int i = 0; i < size; i++)
std::cin >> arr[i];
delete[] arr;
// Two-dimensional array
std::cout << "Enter the size of two-dimensional array ";
std::cin >> sizex >> sizey;
int ** arr_2d = new int*[sizex];
for(int i = 0; i < sizex; i++)
arr_2d[i] = new int[sizey];
for (int i = 0; i < sizex; i++)
{
for(int j = 0; j < sizey; j++)
std::cin >> arr_2d[i][j];
}
// Deleting array completely
for(int i = 0;i < sizex; i++)
delete[] arr_2d[i];
}
$ 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
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Apply for C++ Internship
- Check Programming Books
- Apply for Computer Science Internship
- Practice Programming MCQs
- Check C++ Books