Friday, April 27, 2012

Initialize an array in C

This a simple problem, well, because of it, this problem made me upset sometimes. I think you must be feel it is very trouble to initialize an array by a "for" of loop , like that:
for(........)
       initialize statement

So, I find some tips.  all as follows:
There is no easy way, unless you initialize the value to be 0
int A[10] = {0};  // all elements is 0
static in A[10];  // all elements is 0

if not 0,  you can use the following way
1. one by one, don't overlook the obvious solution
int A[10] = {0, 1,  2, 3, 4, 5, 6, 7, 8 ,9}; // one by one

2. The first few elements
int A[10] = {1, 2}; // initialize to 1, 2, 0, 0 ...

3. Specify some elements
int A[10] = {[5] = 7, [2] = 4};

4.For statically initializing a large array with the same value, without multiple copy-paste, you can use macros:

#define VAL_1X     42
#define VAL_2X     VAL_1X,  VAL_1X#define VAL_4X     VAL_2X,  VAL_2X#define VAL_8X     VAL_4X,  VAL_4X#define VAL_16X    VAL_8X,  VAL_8X#define VAL_32X    VAL_16X, VAL_16X#define VAL_64X    VAL_32X, VAL_32X
int myArray[53] = { VAL_32X, VAL_16X, VAL_4X, VAL_1X };
If you need to change the value, you have to do the replacement at only one place.

4. Specifily, if you use gcc, you can do this
int array[1024] = {[0 ... 1023] = 5};

5. Some another way
If you want to ensure that every member of the array is explicitly initialized, just omit the dimension from the declaration:
int myArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
The compiler will deduce the dimension from the initializer list. Unfortunately, for multidimensional arrays only the outermost dimension may be omitted:
int myPoints[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
is OK, but
int myPoints[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9} };
is not.
See also:

版权声明
本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者Saturn和本文原始地址:
https://ndtm-idea.blogspot.com/2012/04/initialize-array-in-c.html

0 comments:

Post a Comment