2017-07-07 97 views
0

我试图计算一个比率,它在我的分子数组满了0的情况下工作,但是当我在分子数组中有值时会破坏程序。分段违例分段错误C++分子数组中的值

223 Double_t *ratio_calculations(int bin_numbers, Double_t *flux_data) 
224 { 
225   Double_t *ratio; 
226   for(int n = 0; n <bin_numbers; n++) 
227   { 
228     if(0 < flux_data[n]) 
229     { 
230 
231       ratio[n] = ygraph.axis_array[n]/flux_data[n]; 
232     } 
233   } 
234   return ratio; 
235 } 

我不知道为什么会发生,是的,我已经检查了我的数组的长度和他们是一样的bin_numbers的价值。

+3

。您忘了内存分配给比。 – user1438832

+0

@ user1438832您应该将其作为回答发布 –

回答

1

您需要确定正确的大小ratio,分配的内存,最后,请确保您填写ratio 正确地为您提供if声明过滤无效数据:

Double_t *ratio_calculations(int bin_numbers, Double_t *flux_data) { 
    // get correct size 
    int sz = 0; 
    for (int n = 0; n < bin_numbers; n++) { 
    if (flux_data[n] > 0) sz++; 
    } 
    Double_t *ratio = new Double_t[sz]; 
    // allocate with non-n index, as n increments even when data is invalid (flux_data[n] < 0) 
    int r_idx = 0 
    for (int n = 0; n <bin_numbers; n++) { 
    if (flux_data[n] > 0) { 
     ratio[r_idx] = ygraph.axis_array[n]/flux_data[n]; 
     r_idx++; 
    } 
    } 
    return ratio; 
} 
+0

记得在您不再需要时删除比例!或者更好地使用矢量。 – Logman

+0

@Logman。我希望OP知道这一点;)。 OP,'删除[]比率;'当你完成。 –