How do I initialize a 2D array with 0s when I declare it?
double myArray[3][12] = ?
How do I initialize a 2D array with 0s when I declare it?
double myArray[3][12] = ?
double myArray[3][12] = {0};
or, if you want to avoid the gcc warning "missing braces around initializer" (the warning appears with -Wall
or, more specifically -Wmissing-braces
)
double myArray[3][12] = {{0}};
If you want to initialize with zeroes, you do the following:
double myArray[3][12] = { 0 };
If you want to fill in actual values, you can nest the braces:
double myArray[3][3] = { { 0.1, 0.2, 0.3 }, { 1.1, 1.2, 1.3 }, { 2.1, 2.2, 2.3 } };
You may use
double myArray[3][12] = { 0 };
or
double myArray[3][12];
memset(myArray, 0, sizeof(double) * 3 * 12);
pmg's method is correct, however, note that
double myArray[3][12] = {{}};
will give the same result.
Additionally, keep in mind that
double myArray[3][12] = {{some_number}};
will only work as you expect it when some_number is zero.
For example, if I were to say
double myArray[2][3] = {{3.1}};
the array would not be full of 3.1's, instead it will be
3.1 0.0 0.0
0.0 0.0 0.0
(the first element is the only one set to the specified value, the rest are set to zero)
This question (c initialization of a normal array with one default value) has more information
pmg's method works best as it works on the concept that if u initialise any array partially, rest of them get the default value of zero. else, u can declare the array as a global variable and when not initialised, the array elements will automatically be set to the default value (depending on compilers) zero.