tags:

views:

300

answers:

6

How do I initialize a 2D array with 0s when I declare it?

double myArray[3][12] = ?

+8  A: 
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}};
pmg
If you use the paragraph code blocks (four spaces at the beginning of line) you get syntax hightlighting, which you don't if you use inline blocks (backticks).
Martinho Fernandes
Thanks, edited. I was in a backtick mode when I answered :)
pmg
Ok great thanks!
Chris_45
A: 

I think it will be

double myArray[3][12] = {0}
Dani
+3  A: 

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 } };
JSBangs
+1 for pointing out how to initialize everything ... but why did you shorten the array? :P
pmg
I shortened the array because I didn't want to type twelve sets of numbers.
JSBangs
A: 

You may use

double myArray[3][12] = { 0 };

or

double myArray[3][12];
memset(myArray, 0, sizeof(double) * 3 * 12);
Pavel Yakimenko
A: 

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

Charles Sigismund
A: 

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.

Aditya