基于分子数组值的分段违背故障C++

基于分子数组值的分段违背故障C++,c++,arrays,struct,C++,Arrays,Struct,我试图计算一个比率,当我的分子数组充满了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 <

我试图计算一个比率,当我的分子数组充满了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 }

我不知道为什么会发生这种情况,是的,我已经检查了数组的长度,它们与二进制数的值相同。

您需要确定正确的比率大小,分配内存,最后确保填充比率 在使用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;
}

您忘记了分配内存与比率。@user1438832您应该将其作为答案发布。当您不再需要该比率时,请记住删除该比率!或者最好用向量代替。我希望OP知道这一点;。OP,删除[]比率;当你完成的时候。