What are differences between static and dynamic declaration of array

56 Views Asked by At

I am new to C++ programing, I learnt that all the static variables are allocated at compile time on stack memory, so their size should be known before compiling by the compiler.

But the dynamic variables are allocated over heap memory which is very large and compiler doesn't need to know about the size before hand

so I tried out static and dynamic declaration of arrays, and giving them size at runtime but the program is running fine.

So, what's the difference between them apart from fact one is on heap? like both are arrays are of size n only

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

main(){
  int n; 
  cin>>n;
  
  int arr1[n];
  int *arr2 = new int[n];
  
  for(int i=0; i<n; ++i){ 
    arr1[i] = i;
    arr2[i] = i;
  }
  
  for(int i=0; i<n; ++i){
    cout<<arr1[i]<<" "<<arr2[i]<<endl;
  }
  
}

input: 1000

output:

0 0
1 1
2 2
3 3
.
.
.
.
(so on till)
999 999
0

There are 0 best solutions below