Question

I want to initialize a 2D array using the {} initializer but can't get it to work:

int** spiral = new int*[1001]{new int[1001] {0}};

The first row gets allocated and initialized to 0 but none of the other rows do.

This works but I'm pretty sure I can do this without a loop:

int** spiral = new int*[1001];
for (unsigned i = 0; i < 1001; i++)
    spiral[i] = new int[1001] {0};

What am I missing here?

Was it helpful?

Solution

int** spiral = new int*[1001]{new int[1001] {0}};

The C convention of zero initializing arrays with int x[10] = {0}; gives people get the idea that arrays can be initialized by providing a single initializer and that it will be applied to every element. This is a reasonable but incorrect inference. The code int x[10] = {1}; initializes only the first element to that value, and every value for which there is no initializer is zero initialized.

You must either provide an initializer for every element or initialize elements in a loop or somehow explicitly initialize every element.


There are better ways to create such a multi-dimensional array with fixed dimensions. Here's one way:

using arr2d = std::array<std::array<int, 1001>, 1001>;
auto spiral =std::unique_ptr<arr2d>(new arr2d{});
(*spiral)[100][100];

This could be made prettier, but it does the right thing: It uses dynamic allocation to avoid the risk of overflowing the stack, but limits it to a single allocation, and it holds the memory in an exception safe manner.

I'd like to be able to do:

auto spiral = make_unique<array<int, 1001, 1001>>();
spiral[100][100];

And of course implementing the above isn't too difficult, but it hasn't been standardized yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top