When we create an array, for example int arr[2][4];
, its size becomes 2x4x4 = 32, but if we do this dynamically, its size becomes more then 32.
For instance, I wrote this code:
#include <iostream>
#include <stdlib.h>
using namespace std;
// arr[4][2]
int main(){
int **arr;
arr = (int**)malloc(4*sizeof(int*));
int i;
for(i=0;i<4;i++){
*(arr+i) = (int*)malloc(2*sizeof(int));
}
arr[3][1] = 4;
cout << arr[3][1];
return 0;
}
There are 8 + 4x8 + 4x2x4 = 72 bytes allocated. That's why I thought the program is doing different and I wonder how it does this.