Home > Net >  Declare array of double array in C
Declare array of double array in C

Time:05-10

I have declared my double array this way

double feature_values[] = {0.0003323988609746907, 0.6412162477054423, 9.545269768297, -1323.6125512135593, -1512.0718516647562, -2073.6020535721273, -2578.302701605687, 0.27304053703708875, 0.5580326301604825, 0.34912544310755905, 0.550917816717867, 49.7455110651867, 1821.15723334093, -61.3700045037962, -49.400686298507, 13.11111111111111, 26.0, 12.222222222222221, 18.0, 0.3111111111111111, 0.325, 0.4148148148148148, 0.43333333333333335, 0.5930328763108722, 0.7343377194812131, 0.23685155593995189, 0.6754530381265557, 0.16582557525922734, 0.009828988419922594, 0.00017475124235758377, 0.0003779194334627987, 0.0008100853061379151, 2.9387129701088046, 0.41880424639672703, 2.639057329615259, 0.0, 2.75, 2.807354922057604, 0.07124096827009982, 0 , 0.003, 0.1435385870250432, 0.5547574989867142, 0.1445909953802227};
    int index;
    for(int i=0;i<44;i  )
    {
        data[i].missing=-1;
        data[i].fvalue=feature_values[i];
        printf("feature[%d]=%.8f\n",i,feature_values[I]);
        predict_res(data,0,result);
    }

I have 6 different feature_values arrays. And I want to print result for each of them. Currently I need to change the array value every time to get the result. So, how do I declare array of double array and use it in for loop.

CodePudding user response:

C has std::array, which has a size() member. If the size should very at runtime, use std::vector. It too has a size() member.

CodePudding user response:

Just use the std::array for constant sized arrays. This example uses integers, but the concept is the same.

 #include <iostream>
 #include <array>

 typedef std::array<std::array<int, 3>, 2> arr_2d_t;

 int main(int argc, char* argv[]) {
     arr_2d_t arr_2d;
     int num = 0;
     for (size_t i = 0; i < 2;   i) {
         for (size_t e = 0; e < 3;   e) {
             arr_2d[i][e] = num  ;
         }
     }

     for (size_t i = 0; i < 2;   i) {
         for (size_t e = 0; e < 3;   e) {
             std::cout << arr_2d[i][e] << " ";
          }
          std::cout << std::endl;
     }
 }

CodePudding user response:

So How do I declare array of double array and use it in for loop.

The syntax of declaring an array of arrays is this:

double feature_values[6][44];

Note that elements of array are of same type. Hence, you cannot have sub arrays of different lengths.

how do I use it in for loop.

In the same way as any other array. Example:

for(auto& sub_array : feature_values) {
    for(auto& element : sub_array) {
        use_value(element);
  • Related