Pages

Friday, November 24, 2017

Easy tutorial for C / C ++ - class 5 (Dynamic memory allocation (new, delete))

Easy tutorial for C / C ++ - class 5 (Dynamic memory allocation (new, delete))

Dynamic memory allocation (new, delete) :

- Let's review the dynamic memory allocation using the 'new' operator. I have used variables and arrays in the previous examples. In general, a variable or array that you declare will allocate memory and use it in a 'stack'. The size of the memory space is determined when compiling, and the size of the memory space can not be changed during program execution. This is called static memory allocation.

- There is an area called 'heap' that can be used until the programmer explicitly releases the memory. While programmers have the advantage of being free to adjust, they also have administrative responsibilities.

- You can also allocate as much memory space as you want (even during program execution). This allocation of memory space at runtime is called dynamic memory allocation.

- Dynamic memory allocation can be allocated through the 'new' operator. The allocated space is managed by a pointer variable. And the memory space allocated by 'new' operator must be released by 'delete'. To declare an array with dynamic memory allocation is as follow:

usage)

allocation : 'pointer variable' = new 'datatype' ['number of element'];
deallocation : delete [] 'pointer variable';

- Let's look at a simple example using arrays.

Example Code

#include <iostream>
using namespace std;

int main() {

          int n ;
          cout << " Size of array = ";
          cin >> n;

          int *a;
          a = new int[n];

          for(int i=0; i < n; i++){
                   cout << "a[" << i << "] = " ;
                   cin >> a[i] ;
          }

          cout << endl;

          for(int i=0; i < n; i++){
                   cout << "a[" << i << "] = " << a[i] << endl ;
          }
          delete []a;
           return 0;
}

- First we declare integer variable 'n' to store the size of the array, and input the size of array through cin object. We declare pointer variable 'a' and use 'new' operator to point to the array allocated memory space in the heap area.

- For for loop, input the value to each element of array and output the result.

- You have used delete to release the space allocated by the new operator. Where '[]' indicates that the array to be released is an array.

results :

 Size of array =

- You are prompted to enter the size of the array. Here we enter 7, and then we assign 1,2,3,4,5,6,7 to the elements of the array. 

 Size of array = 7
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7

- You can see that the element value of the input array is output.

No comments:

Post a Comment