In C++ you can initialize a one dimensional array with 0 with a code like this:
int myarray[100] = {0};
Is there a similar way for multidimensional arrays? Or am i forced to initialize it manually with for loops?
You do it exactly the same way
int marr[10][10] = {0};
Edit:
This is a C solution. For a C++ solution you can go for:
int marr[10][10] = {};
These 2 solutions do not work for arrays that have size defined via variables. e.g.:
int i, j = 10;
int marr[i][j];
To initialize such an array in C++ use std::fill.
const int N = 10; int myarray[N][N] = {0};memset.memset for this task! While it would work in this particular case, there are too many pitfalls. This is C++, not C. Use std::fill.memset here would be.A multidimensional array is an array of arrays.
The same general array initialization syntax applies.
By the way you can just write {}, no need to put an explicit 0 in there.
int myarray[10][20] = {}; instead.use vector instead of array it will give you more flexibility in declaration and in any other operation
vector<vector<int> > myarray(rows,vector<int>(columns, initial_value));
you can access them same as you access array,
and if u still want to use array then use std::fill
You could use std::memset to initialize all the elements of a 2D array like this:
int arr[100][100]
memset( arr, 0, sizeof(arr) )
Even if you have defined the size via variables this can be used:
int i=100, j=100;
int arr[i][j]
memset( arr, 0, sizeof(arr) )
This way all the elements of arr will be set to 0.
For "proper" multi-dimensional arrays (think numpy ndarray), there are several libraries available, for example Boost Multiarray. To quote the example:
#include "boost/multi_array.hpp"
#include <cassert>
int
main () {
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
// Verify values
int verify = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
assert(A[i][j][k] == verify++);
return 0;
}
int myarray[100] = {0};only initializes the first element to0, if you said for example={5}, the array would contain{5, 0, 0, 0...}.={0}since the value initializedintis 0.{0}. With other values, yes, you're correct, but{0}is special in this case.memsetin C++, prefer at leaststd::fill