I have come across some code which allocates a 2d array with following approach:
auto a = new int[10][10];
Is this a valid thing to do in C++? I have search through several C++ reference books, none of them has mentioned such approach. Normally I would have done the allocation manually as follow:
int **a = new int *[10];
for (int i = 0; i < 10; i++) {
a[i] = new int[10];
}
If the first approach is valid, then which one is preferred?
*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".
The syntax for new is : type* ptr = new type; // allocate memory for a single type variable. Eg - int* ptr = new int; One can also use new to allocate contiguous blocks of memory like an array. Eg - int* arr = new int[20]; // Array of size 20.
new allocates an amount of memory needed to store the object/array that you request. In this case n numbers of int. The pointer will then store the address to this block of memory.
There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.
The first example:
auto a = new int[10][10];
That allocates a multidimensional array or array of arrays as a contiguous block of memory.
The second example:
int** a = new int*[10];
for (int i = 0; i < 10; i++) {
a[i] = new int[10];
}
That is not a true multidimensional array. It is, in fact, an array of pointers and requires two indirections to access each element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With