X 处的指令引用了 Y 处的内存.内存无法读取

the instruction at x referenced memory at y.The memory could not read

本文关键字:内存 读取 指令 引用      更新时间:2023-10-16

当我运行此代码时,计算机显示内存错误

X 处的指令引用 y 处的存储器。无法读取内存

#include<cstdlib>
using namespace std;
class Matrix{
private:
int row,col,**ptr;
public:
Matrix();
void create(int,int);
void show();
Matrix multiply(Matrix);
};
Matrix::Matrix()
{
row=0;
col=0;
ptr=NULL;
}
void Matrix::create(int r,int c)
{
row=r;
col=c;
ptr=new int* [row];
static srand(time(0));
for(int i=0;i<row;++i)
{
ptr[i]=new int[i+1];
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
ptr[i][j]=rand()%6+1;
}
}
}
Matrix Matrix::multiply(Matrix obj2)
{
if(col==obj2.row)
{
Matrix temp;
for(int i=0; i<row; ++i)
{
for(int j=0; j<obj2.col; ++j)
{
temp.ptr[i][j]=0;
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<obj2.col;j++)
{
for(int k=0;k<col;k++)
{
temp.ptr[i][j]+=ptr[i][k]*obj2.ptr[k][j];
}
}
}
return temp;
}
else
{
cout<<"Conditions are NOT fulfill for Multiplication"<<endl;
}
}
void Matrix::show()
{
cout<<"Matrix: "<<endl;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<ptr[i][j]<<"t";
}
cout<<endl;
}
}
int main()
{
Matrix obj1,obj2,obj3;
obj1.create(2,2);
obj1.show();
obj2.create(2,2);
obj2.show();
obj3=obj1.multiply(obj2);
obj3.show();
}

程序应乘以矩阵并存储在第三个对象中,但发生错误。 我不知道问题出在哪里。 这就是我发送整个代码的原因。

程序正在读取分配内存的末尾。在create方法中,没有分配足够的空间来存储整行元素:

void Matrix::create(int r,int c)
{
row=r;
col=c;
ptr=new int* [row];
static srand(time(0));
for(int i=0;i<row;++i)
{
ptr[i]=new int[i+1]; // <- the allocation is here
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++) // <- you iterate j from 0 to col here
{
ptr[i][j]=rand()%6+1; // <- and then access here
}
}
}

由于您正在分配 i+1 元素,因此第一行只有足够的空间容纳单个元素,第二行具有容纳两个元素的空间,依此类推。修改分配以col元素腾出空间应该可以解决此问题。