0

我有一个返回双精度数组的函数。在我的调试器中,我检查了数组,发现它的值为 {6.5, 1.5}。但是,当我将数组打印到 cout 时,我看到“6.5,3.30525e+230”。我的猜测是 << 正在改变我的值或者我没有正确格式化

double *result;

result = haar1d(series, 2, seriesAverage);

--> 在断点处,我看到了 result[0] == 6.5 和 result[1] == 1.5

for(int i = 0; i < 2; i++)
{
    cout << result[i] << ",";
}

固定:这就是我最终得到的。

vector<double> haar1d(vector<double> vec, double seriesAverage)
{
vector<double> transVec(vec.size(), 0);
vector<double>::size_type length = vec.size();

if(vec[0] == seriesAverage)
{
    return vec;
}

int diffFromAvgs = length / 2;

for(int i = 0; i < length; i += 2)
{
    double pairAverage = (vec[i] + vec[i + 1]) / 2;
    transVec[i] = pairAverage;
    transVec[diffFromAvgs+i] = vec[i] - pairAverage;
}

return haar1d(transVec, seriesAverage);
}

主要:

vector<double> result = haar1d(series, avg);

for(vector<double>::iterator it = result.begin(); it != result.end(); ++it)
{
    cout << *it << ",";
}
4

1 回答 1

6

No, operator<< does not modify its arguments. It prints them as is. However, I bet your function looks something like this:

double* haar1d(/* ... */)
{
  double arr[N];
  // Fill this array
  return arr;
}

The point being that the array arr is local to the function. It will be destroyed when the function ends. However, you're returning a pointer to its first element. That pointer will be invalid outside the function, because the array it points to has been destroyed. To use this pointer now will invoke undefined behaviour, so you shouldn't be surprised if values start changing seemingly randomly.

I recommend using either std::array<double, N> or std::vector<double>, depending on whether your array size is a compile time constant or not. Returning either of these will copy its contents to the calling function.

If I'm guessing correctly, you might be using the argument that you gave as 2 as the size of the array. If this is compiling, you are using a compiler with a variable length arrays extension, and your code is not standard C++.

于 2013-01-12T18:15:40.307 回答