0

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?

4
  • @KerrekSB, tbh vectors of vectors is not an excellent idea. Maybe a single one? Commented Apr 2, 2014 at 19:41
  • No I did not intend on using std::vector and certainly did not want to nest them. Commented Apr 2, 2014 at 19:47
  • @ScottR, why not use std::vector? Commented Apr 2, 2014 at 19:49
  • I suppose I could. This project is more for learning how to use some of the new stuff from C++11 and the {} initializers seemed cool but I can't get it to work like I thought it should. Commented Apr 2, 2014 at 19:52

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I did not know this: "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." I'd seen examples and written with a single {0} and every element was 0 so I assumed it worked that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.