2

For a fixed array,

  // will initialize the missing elements to 0 as well
   A[max_row][max_col] = {0,} 

Can we achieve this in dynamic arrays (multidimensional, in particular)?

Side question: if we can't, and we are forced to use nested loop, then how does the initialization time of the trick above compared to nested loop initialization?


I don't want to vector, otherwise this question is meaningless. Thanks for the advise :)

16
  • 1
    I know you can do that. Everyone wants to use vector, but I don't want to. I am sorry I forgot to include that. Thanks though. Commented Nov 27, 2011 at 5:14
  • 1
    Regarding your first question: What happened when you tried? Regarding your second question: Internally C++ represents a multi-dimensional array as a single flat list of memory locations of type "whatever" (where whatever is how you invoked new). You don't need a nested for loop if you do it that way. You can just use a pointer to run through row x col number of positions with a single loop. Commented Nov 27, 2011 at 5:17
  • 1
    Why don't you want to? Just for understanding (practice), or for real use? Commented Nov 27, 2011 at 5:18
  • 1
    Exact Duplicate of How do you initialise a dynamic array in C++? Commented Nov 27, 2011 at 5:20
  • 3
    @CppLearner: No. The overhead of a std::vector (if it even exists at all, which I believe it doesn't) is absolutely trumped by the gains in maintainability and program correctness. Commented Nov 27, 2011 at 5:27

1 Answer 1

12

If you do this: new int[N]() /* note parenthesis */, then they are all zero initialized.

You should really use a std::vector, though.

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

Comments

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.