分段冲突 分子数组中值的分段错误 c++

segmentation violation Segmentation fault c++ with values in numerator array

本文关键字:分段 错误 c++ 数组 冲突      更新时间:2023-10-16

我正在尝试计算一个比率,当我的分子数组充满 0 时它可以工作,但是当我在分子数组中有值时会破坏程序。

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的值相同。

您需要确定正确的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;
}