Reputation: 1
I was solving a problem on sum of submatrices, I declared my 2d-array as
int a[i][j] ; //i =number of rows and j = number of columns
my code executed properly. But when I saw the solution i saw these lines :
int **arr = new int * [n] ;
for (int i = 0 ; i < n ; i++)
{
arr[i]=new int [m];
}
// n -> number of rows and m -> number of columns.
I understand the code. why the solution(given on some random website) is using pointers. If we can do it using the above normal declaration. It will make the code faster or something?
Upvotes: 0
Views: 921
Reputation: 329
Both ways of array declaration are useful in different use cases. The declaration:
int a[i][j];
declares an array statically and it uses stack memory to store the array or we can say that the memory is allocated at the runtime. This type of array declaration requires you to pass the value 'n' and the size of the array can not be altered after it's been declared. That's where it has a drawback as you can not increase the size if you want to store some more elements. Also if you stored less elements than 'n', then the remaining memory gets wasted. The other type of declaration:
int *a = new int[n]; //For 1D array
creates a dynamically allocated memory. In other words, in this type of declaration memory allocation takes place only when an element is placed in the array or at the runtime. This allocation ensures that there is no memory wastage and stores the elements of the array in the heap memory. But in this type of declaration, you also need to deallocate the memory otherwise it may cause memory leaks because C++ has nothing like a garbage collector.
Upvotes: 0
Reputation: 310960
This declaration
int a[i][j] ; //i =number of rows and j = number of columns
requires that the variables i
and j
would be compile-time constants. Variable length arrays is not a standard C++n feature though some compilers can have their own language extensions that include this feature.
The second problem that exists is if sizes of an array are too big then the compiler can be unable to create such an array with automatic storage duration.
So if i
and j
are not compile-time constants or are too big then you have to allocated memory dynamically yourself or you can use the standard container std::vector
.
Upvotes: 2
Reputation: 13
If we can do it using the above normal declaration. It will make the code faster or something? no all in above code you create an array in the stack it will be deleted if the function out of scope it will be removed automatically
the second is created in heap it will still in the heap until u delete it by self
Upvotes: 0