How does delete[] “know” the size of the operand array in C++


New operator is used for dynamic memory allocation which puts variables on heap memory. Delete[] operator is used to deallocate that memory from heap. New operator stores the no of elements which it created in main block so that delete [] can deallocate that memory by using that number.

Example Code

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int B = 4;
   int A = 5;
   int** a = new int*[B];
   for(int i = 0; i < B; ++i)
      a[i] = new int[A];
   for(int i = 0; i < B; ++i)
      for(int j = 0; j < A; ++j)
         a[i][j] = i;
   for(int i = 0; i < B; ++i)
      for(int j = 0; j < A; ++j)
         cout << a[i][j] << "\n";
   for(int i = 0; i < A; ++i)
      delete [] a[i];
      delete [] a;
   return 0;
}

Output

0
0
0
0
0
1
1
1
1
1
2
2
2
2
2
3
3
3
3
3

Updated on: 30-Jul-2019

584 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements