意外的数组导致c ++

时间:2015-04-13 02:45:44

标签: c++ arrays

这是一个棘手的问题,但我不知道该转向何处。从一开始就总结一下,我在使用c ++中的数组时遇到了麻烦。为了避免不可避免的响应,我必须使用数组,我不能使用向量。原因是我最终会将其与CUDA接口,而CUDA无法接受矢量。

无论如何,我已经编写了自己的类来处理2D数组以及幕后所有的东西。头文件在此问题的底部重现。我用这个类来定义一个6 x 10的数组。然后,我主要使用我的类的add方法循环遍历许多项。在这个复杂的循环中的某个时刻,我的数组的大小从6 x 10切换到0 x 1074266112.我试图调试我的代码并弄清楚问题是什么,但对于我的生活,我找不到问题。 / p>

我已经打印出数组大小更改时的所有值,并且没有一个超出常规,我永远不会尝试将数组索引到6x10大小之外。实际上,它甚至从未发生在循环的同一点,它似乎只是在每次运行时随机发生。我可以在每个问题之间找到的唯一常量是新数组大小始终精确为0 x 1074266112。

抱歉,我无法提供最低限度的工作示例,但是这个问题只出现在我的大型程序中,我无法在较小的程序中重现它。我至少希望有人能看到我在下面的Matrix程序中做错了什么,并且可能建议一种调试方法。

编辑:如果我将其更改为使用向量而不是数组,则问题就会消失。即,如果我将相关部分更改为vector<double> data并在实例化data = *(vector<double>(x * y))时,上述问题不再是问题。但是我不知道将这个数组作为一个什么问题。

#include <vector>
#include <iostream>
#ifndef MATRIX_H
#define MATRIX_H

using std::vector; using std::cout; using std::endl;

class Matrix {
    //Define the private variables associated with any instance of this class.
    double * data;      //The 1D pointer which points to the array
    int w, h;           //The width and height of the 2D array that the 1D data array represents
public:

    Matrix(){}
    Matrix(int x, int y){ setSize(x,y); }

    void setSize(int x, int y){ w = x; h = y; data = new double[x * y]; setAll(0); }

    //Two methods to get the height and width of the effective 2D array
    int getWidth(){ return w; }
    int getHeight(){ return h; }

    //Several methods used to set and get the values of elements within the array as well as extracting
    //rows and columns as vectors.
    void set(int x, int y, double value){ data[y*w + x] = value; }
    void setAll(double value);
    double get(int x, int y){ return data[y*w + x]; }
    vector<double> getCol(int x);
    vector<double> getRow(int y);

    //Several methods to adjust the current value by the input
    void increment(int x, int y){ data[y*w + w] += 1; }
    void add(int x, int y, double value){ data[y*w + x] += value; }
    void subtract(int x, int y, double value){ data[y*w + x] -= value; }
    void multiply(int x, int y, double value){ data[y*w + x] *= value; }
    void divide(int x, int y, double value){ data[y*w + x] /= value; }

};

void Matrix::setAll(double value){
    for (int i = 0; i < w*h; i++){
        data[i] = value;
    }
}

vector<double> Matrix::getCol(int x){
    vector<double> column(h);
    for (int i = 0; i < h; i++){ column[i] = data[i*w + x]; }
    return column;
}

vector<double> Matrix::getRow(int y){
    vector<double> row(w);
    for (int i = 0; i < w; i++){ row[i] = data[y*w + i];    }
    return row;
}

#endif  /* MATRIX_H */

1 个答案:

答案 0 :(得分:1)

您的increment方法错了;它仅取决于y,从上下文看起来您打算在数组索引计算中也使用x。如果您在程序的某个地方调用此increment,那么您可能会在某处的la-la land中写入内存。我不知道这是否是导致问题的唯一原因,但无论如何它都会以无用的方式破坏你的堆。