http://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c

If your compiler is GCC you can use following syntax:

int array[1024]={[0...1023]=5};

 

//================================================================================================================

// description,   initialize a array 

 

//----------- header  x_marco.h

//     Marco filter  (var_name, array_index, var_value)

MARCO_ITEM_FILTER(name_1,   [0] ,  8 )

MARCO_ITEM_SHOW(name_2,    [1],  21)

MARCO_ITEM_SHOW(name_3,    [2],  7  )

MARCO_ITEM_SHOW(name_4,    [3],  9  )

MARCO_ITEM_FILTER(name_5,   [4],  18)

 

//----------  c code  main.c

// we need initial an array g_value_array[5] with the initial value described in x_marco.h

#define MARCO_ITEM_FILTER(var_name, array_index, var_value)            var_name

#define MARCO_ITEM_SHOW(var_name, array_index, var_value)             var_name,

enum {                                                               //  enum{

                                                                          //            name_1,

#include x_marco.h                                            //           name_2,                                               

      kNumberOfShowItem                                   //           name_3, 

};                                                                       //            name_4,

                                                                          //            name_5,

                                                                          //            kItemNumber

                                                                          //   };

                                                                          // in here, we get kItemNumber = 5

 

#undef MARCO_ITEM_FILTER

#undef MARCO_ITEM_SHOW

 

#define MARCO_ITEM_FILTER(var_name, array_index, var_value)             /* filter out useless item */

#define MARCO_ITEM_SHOW(var_name, array_index, var_value)             array_index  = var_value,

int g_value_array[kItemNumber] = {                   //              int g_value_array[5] = {

#include x_marco.h                                              //                       [1] = 21,

};                                                                         //                        [2] = 7 ,

                                                                            //                        [3] = 9,

                                                                            //                }

#undef MARCO_ITEM_FILTER

#undef MARCO_ITEM_SHOW

 

int main(void)

{

    for(int item = 0; item < kItemNumber; ++item}{

        std::cout << "item index  " << item << " = " << g_value_array[item] << endl;

    }

    return 0;

}

 

//--------- output

>> item index  0 = 0

>> item index 1 = 21

>> item index 2 = 7

>> item index 3 = 9

>> item index 4 = 0 

arrow
arrow
    全站熱搜

    阿肯 發表在 痞客邦 留言(0) 人氣()