Search code examples
c++arraysnew-operator

What is the difference between allocating array like int a[10][10] and allocating array using new keyword in c++?


I am presently using Windows 10 with gcc version 6.3.0 (MinGW.org GCC-6.3.0-1).
Code 1

#include <bits/stdc++.h>
using namespace std;

int main(){
    int** a = new int*[100000];
    for(int i = 0; i < 100000; ++i)
        a[i] = new int[1000];
    cout << "Array allocation Ok!!!\n";
    return 0;
}

//Output
Array allocation Ok!!!

Code 2

#include <bits/stdc++.h>
using namespace std;

int main(){
    int arr[100000][1000];
    cout << "Array allocation Ok!!!\n";
    return 0;
}

//I got no Output, it just return the console back to me

Someone suggested me the difference could be that in Code 2 row i and i+1 are contiguous (row major representation) i.e. int arr[1000][100] is same as int arr[100000] in terms of memory. But in Code 1 the column entries are contiguous in nature but not the rows. But if that could be the case then what about pointer arithmetics?


Solution

  • The short answer is that a[10][10] is allocated on the stack and the array being allocated with new is allocated on the heap.