c++ - 动态数组堆损坏

标签 c++ dynamic corruption heap-corruption

我有以下类(class):

template <typename T>
class matrix
{
private:
    int _n;
    T* array;
public:
    matrix(): _n(0) 
    {
        array = new T[_n * _n];
    }
    matrix(int n): _n(n)
    {
        if( n < 0 )
            throw "Invalid array size!";
        array = new T[_n * _n];
    }
    ~matrix()
    {
        delete[] array;
    }
    void Set(const int x, const int y,const T val)
    {
        if( ( x<0 || x>_n ) && ( y<0 || y>_n) )
            throw "Invalid index";
        array[x*_n + y] = val;
    }
    T& Get(const int x, const int y)
    {
        if( ( x<0 || x>_n ) && ( y<0 || y>_n) )
            throw "Invalid index";
        return array[x*_n + y];
    }
};

并以这种方式使用它:

matrix<int> k(5);
k.Set(5,5,6);
cout<<k.Get(5,5);

问题是我在调用 Set 时遇到堆损坏错误。 我究竟做错了什么? (我猜这是我访问数组元素的方式)

最佳答案

可以在索引 0-4 处访问 5 元素数组。您为 xy 传递 5,这会导致访问 array 时索引无效。

关于c++ - 动态数组堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10056390/

相关文章:

postgresql - Postgres 将列出我的数据库,但当我尝试连接到它时它不存在

ffmpeg jpg 帧捕获 - 如何丢弃损坏的帧

c++ - 关于multi-probe Local Sensitive Hashing的问题

c++ 应用程序在非 AVX CPU 上崩溃

python - Tkinter 如何在不使用字典的情况下制作动态选项菜单

java - POI 3.2 Excel 文件数据丢失

c++ - 我如何比较 C 或 C++ 中数组的内容

c++ - pthread_create创建的子线程如何调用主线程?

c - 如何在 C 中使用动态多维数组?

c++ - 定义动态结构