Initializing a two-dimensional dynamic array

I am trying to initialize all the elements of a two-dimensional array when declaring it:

int** ints = new int* [n] { new int[n] { 0 } };

When trying to output the elements

for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            cout << "i = " << i << "; j = " << j << "; value = " << ints[i][j] << endl;

I get this result in the console:

i = 0; j = 0; value = 0
i = 0; j = 1; value = 0
i = 0; j = 2; value = 0
i = 1; j = 0; value =

An exception is raised: нарушение прав доступа при чтении по адресу 0x0000000000000000.

I can't figure out what's going on.

n = 3.


When outputting elements of a one-dimensional array initialized in this way:

int* ints = new int[5];

The console displays

-842150451
-842150451
-842150451
-842150451
-842150451

, and such:

int* ints = new int[5] { 0 };

-

0
0
0
0
0

.

Author: Имя Фамилия, 2019-11-08

1 answers

When initializing an array with the specified size, the missing initializers are zeros. I.e.

int a[5] = {6};

Fills the array a with the values 6,0,0,0,0.

Note-initialization by value, not by expression evaluation :)

int i = 0;
int a[5] = {i++};

Will not apply i++ to all array elements.

What does

new int* [n] { new int[n] { 0 } };

? The single value new int[n] { 0 } is calculated and assigned to the first element of the array. The rest are filled in with zeros. Is the rest clear? :)

If you want to use exactly C++, and not some mutated C, then vector is in your hands:

vector<vector<int>> ints(n, vector<int>(n,0));

And no worries with freeing up memory :)

Update

On an extended question - in the complete absence of an initializer as such, no initialization is performed, and the array is filled with garbage as a result.

 2
Author: Harry, 2019-11-08 20:46:35