How does a C++ program allocate memory for an array?(NOT DYNAMICALLY)

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.

Upvotes: 0

Views: 83

Answers (2)

Barmar
Barmar

Reputation: 780851

int arr[4][2] allocates a single block of memory, with indexes laid out like this:

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

Each element is 4 bytes to hold an int.

In your dynamic allocation method, you have 8 bytes for the arr variable itself. Then the first malloc() allocates an array like this:

ptr0 ptr1 ptr2 ptr3

This is 4x8 bytes.

Then you call malloc(2 * sizeof(int)) 4 times, which allocates 4x2x4 bytes.

Upvotes: 1

dbush
dbush

Reputation: 223739

What you've done here isn't exactly a 2D array although it behaves like one syntactically. What you instead have is an array of pointers, and each of those pointers points to an array of int.

If you want to allocate an actually 2D array you would do so like this:

int (*arr)[2] = malloc(4 * sizeof *arr);

Upvotes: 3

Related Questions