Chris_45
Chris_45

Reputation: 9063

Initialize a 2D-array at declarationtime in the C programming language

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

double myArray[3][12] = ?

Upvotes: 40

Views: 136902

Answers (7)

Rainald62
Rainald62

Reputation: 740

The memory layout may be relevant (e.g., for serialization).

myArray[3][2] = { { 0.1, 0.2 }, { 1.1, 1.2 }, { 2.1, 2.2 } };

The first index is the row index is the slowest index. This is known as C order as opposed to F (Fortran) order.

Upvotes: 13

Aditya
Aditya

Reputation: 1

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.

Upvotes: 0

Cody Schafer
Cody Schafer

Reputation: 361

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

Upvotes: 10

Pavel Yakimenko
Pavel Yakimenko

Reputation: 3254

You may use

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

or

double myArray[3][12];
memset(myArray, 0, sizeof(double) * 3 * 12);

Upvotes: 2

pmg
pmg

Reputation: 108986

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}};

Upvotes: 54

JSBձոգչ
JSBձոգչ

Reputation: 41388

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 } };

Upvotes: 22

Dani
Dani

Reputation: 15079

I think it will be

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

Upvotes: 1

Related Questions