Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is new int[][] a valid thing to do in C++?

Tags:

c++

c++11

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?

like image 665
crab oz Avatar asked Oct 03 '15 10:10

crab oz


People also ask

What does new int do in C?

*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".

Can we use new with int?

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.

What is the use of new int?

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.

CAN new be used in C?

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.


1 Answers

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.

like image 84
Galik Avatar answered Oct 04 '22 18:10

Galik