X 处的指令引用了 Y 处的内存.内存无法读取
the instruction at x referenced memory at y.The memory could not read
当我运行此代码时,计算机显示内存错误
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
元素腾出空间应该可以解决此问题。
相关文章:
- 我无法从内存中读取值
- 如何读取特定地址的进程内存?
- 使用 OpenSSL 从内存中读取原始 SSL/TLS 证书
- 如何在 WSL 2 中读取物理内存?
- 如何使用带有矢量的 winapi 读取进程内存从另一个进程读取缓冲区?
- 从只读内存中读取结构
- 当注入程序的内存空间时,如何读取从 0 到 0xFFFFFFFFF 的每个字节?我正在创建模式扫描仪
- 如何运行外部程序,向其传递内存地址以读取/写入?
- C++指针将内存读取为 0
- 读取进程内存多级指针(DLL 注入)
- 组织从内存读取的数据的最佳方法(用于调试)c++
- 使用ClgetDeviceInfo从内存读取访问违规
- C++ - 分叉进程无法从共享内存读取
- C# 简化多指针的内存读取
- Linkedlist内存读取错误
- 从原始内存读取值(符合MISRA)
- c++ DLL内存读取崩溃
- 在wwpal rabbit中从内存读取数据
- c++中什么是预内存读取?
- 优化内存读取和写入的长期运行