我正在处理一个与c ++中的动态分配有关的问题。我有以下函数来计算信号的均方根
void FindRMS(int points, double* signal_x, double* signal_y, int presamples, double* mean, double* rms)
{
//double fraction_presamples_RMS = 0.9; // fraction of presamples to calculate RMS
//Safety condition
if (presamples>points) {
printf("\nERROR: Too many presamples!\n\n");
return;
}
//Main procedure
(*rms) =0.;
(*mean) =0.;
for (int i=0; i<presamples; i++) {
(*mean)+=signal_y[i];
(*rms)+=pow(signal_y[i],2);
}
(*mean)/=presamples;
(*rms)=sqrt((*rms)/presamples-pow((*mean),2));
cout << "RMS was found to be : " << (*rms) << endl;
}
首先,如果我理解正确,double* <var>
意味着该参数应该是动态定义的,这意味着它的大小将受到硬件的限制。
然后我做的是在我的代码中调用这个函数。示例代码如下
void Analyze(unsigned int first_run, unsigned int last_run, unsigned int last-segment){
int points = 9e6;//hSignal->GetNbinsX();
//double x[points], y[points], derivative[points]; // SIZE limited by COMPILER to the size of the stack frame
double* x = new double[points]; // SIZE limited only by OS/Hardware
double* y = new double[points];
double* derivative = new double[points];
double* mean = new double[points];
double* rms = new double[points];
for (int i = 0; i < points; i++){
x[i] = hSignal->GetBinLowEdge(i+1);
y[i] = hSignal->GetBinContent(i+1);
//cout << " Bin Center " << hSignal->GetBinLowEdge(2) << endl;
}
FindRMS(points, x, y, 0.9*points, mean, rms);
delete[] x;
delete[] y;
delete[] mean;
cout << "The value of rms[10] = " << rms[10] << endl;
}
奇怪的是,当程序执行时,我从函数中得到一个带有逻辑rms的cout,而在程序结束之前我得到的rms是0。
有关为何发生这种情况的任何想法或建议?问题是我必须坚持使用该功能,因为它属于我必须坚持使用的库...
我想改变函数以返回double*
而不是void
,但实际上没有任何改变......这是修改后的函数
double* FindRMS(int points, double* signal_x, double* signal_y, int presamples, double* mean, double* rms)
{
//double fraction_presamples_RMS = 0.9; // fraction of presamples to calculate RMS
//Safety condition
if (presamples>points) {
printf("\nERROR: Too many presamples!\n\n");
//return;
}
//Main procedure
(*rms) =0.;
(*mean) =0.;
for (int i=0; i<presamples; i++) {
(*mean)+=signal_y[i];
(*rms)+=pow(signal_y[i],2);
}
(*mean)/=presamples;
(*rms)=sqrt((*rms)/presamples-pow((*mean),2));
cout << "RMS was found to be : " << (*rms) << endl;
return rms;
}
答案 0 :(得分:3)
在函数FindRMS
中,您只设置*rms
,它与rms[0]
相同。数组中的所有其他值都是未初始化的,这意味着它们的值将是不确定(并且似乎是随机的)。读取那些未初始化的值将导致未定义的行为。