【问题标题】:C++ programm stops without a reason on a random position [closed]C ++程序在随机位置无故停止[关闭]
【发布时间】:2015-01-11 16:59:11
【问题描述】:

我正在开发一个 C++ 程序,该程序应该将火焰强度的 2D 图像转换为 3D 模型。该程序主要处理多个矩阵运算,我都使用指针实现了这些运算(我知道,我可以使用向量)。 在文本文件的输入,数据值的镜像和平滑之后,对图像的每一行进行校正计算。在此计算的函数开始时,程序停在一个随机位置,但在声明 y_values-vector 的 for 循环中。

这里是代码片段:

void CorrectionCalculation(Matrix Matrix_To_Calculate, int n_values, int polynomial_degree, int n_rows)
{
    for (int h = 0; h < n_rows; h++)
    {
        //Initialising and declaration of the y_values-vector, which is the copy of each matrix-line. This line is used for the correction-calculation.
        double* y_values = new double(n_values);
        for (int i = 0; i < n_values; i++)
        {
            y_values[i] = Matrix_To_Calculate[h][i];
        }

        //Initialisiing and declaration of the x-values (from 0 to Spiegelachse with stepwidth 1, because of the single Pixels)
        double* x_values = new double(n_values);
        for (int i = 0; i < n_values; i++)
        {
            x_values[i] = i;
        }

计算单行时,程序运行良好。但是当我添加一些代码来计算整个图像时,程序停止了。

【问题讨论】:

  • double* y_values = new double(n_values); 这不会创建一个数组,而是一个双精度元素。修正后程序表现如何(有两个)?
  • “无缘无故”。是的,你的程序很完美,C++ 的设计者是怎么想的。
  • 你是对的,我应该写“没有明显的理由(对我来说和目前)”。 y_values 和 x_values 的初始化是我忘记使用 [] 而不是 () 的唯一情况。不知道失败很烦人,但似乎我站在管道上。

标签: c++ pointers matrix


【解决方案1】:

您分配的不是一个值数组,而是一个元素。 而不是:

double* y_values = new double(n_values);
// ...
double* x_values = new double(n_values);

改成

double* y_values = new double[n_values];
//...
double* x_values = new double[n_values];

你应该使用双精度的vector 而不是新的数组。这样,当不再需要时,内存将被自动删除。例如:

#include <vector>
std::vector<double> y_values(y_values);

你也是hiding variables,通过使用与参数相同的变量名。这可能会导致代码中的混乱和细微错误,您不确定要更改哪个变量。

【讨论】:

  • 似乎这是程序在这个位置停止工作的错误......很烦人;)。非常感谢你。我还必须在 x_values 的初始化上编写这种格式。尽管如此,它仍然停止......现在试图找出错误。
  • “考虑使用向量”还不够强大。除非您有经验并且真的知道自己在做什么,否则没有理由使用数组 new。我不记得在十年的 C++ 编程中合法地使用过它。
  • 好的,我将使用向量。我只是使用数组,因为我们一直认为这样做 - 我认为这主要是因为理解 C++。感谢您的支持。
猜你喜欢
  • 2013-07-27
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多