How can I zero a 2D array in C++? Do I need two for loops just for that?
Coming from other higher languages, I wonder why C++ doesn't initialize arrays to meaningful/sensible defaults? Do I always need to declare an array then "zero" it out right afterwards?
You can loop over a two-dimensional array in Java by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other.
For a two-dimensional array, in order to reference every element, we must use two nested loops. This gives us a counter variable for every column and every row in the matrix.
Accessing 2D Array Elements In Java, when accessing the element from a 2D array using arr[first][second] , the first index can be thought of as the desired row, and the second index is used for the desired column. Just like 1D arrays, 2D arrays are indexed starting at 0 .
C++ language tries to follow the principle of "you don't pay for what you don't use". It doesn't initialize fundamental types to any default values because you might not want it to happen. In any case, the language provides you the opportunity to explicitly request such initialization.
At the moment of declaration you can use initializers and simply do this
int array[10][20] = {};
or, for a dynamically allocated array
int (*array)[20] = new int[10][20]();
and this will give a zero-initialized array. No loops necessary.
But if you want to zero-out an existing array, then you will indeed have to use something more elaborate. In case of integer types a good old memset
will work. For pointer or floating-point types the situation is in general case more complicated. memset
might work or it might not work, depending on the implementation-defined properties. In any case, the standard library can help you to reduce the number of explicit loops by providing such loop wrappers as std::fill
.
Depends how you create it.
Two-dimensional vector, yes, two for-loops (because integers are primitive types - classes will call the default ctor).
Two-dimensional array? No, you can memset
or bzero
at once as the memory is all contiguous, whether using malloc
or new
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With