开发者

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

开发者 https://www.devze.com 2022-12-11 05:40 出处:网络
How do I initialize a 2D array with 0s when I declare it? double myArray[3]开发者_开发问答[12] = ?double myArray[3][12] = {0};

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


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.


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


I think it will be

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


You may use

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

or

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消