【问题标题】:the instruction at x referenced memory at y.The memory could not readx处的指令引用了y处的内存。内存无法读取
【发布时间】:2019-10-06 14:03: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();
}

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

【问题讨论】:

  • 欢迎来到 Stackoverflow。您的代码不应编译,因为static srand(time(0)); 是语法错误。请提供您实际运行的代码。
  • 这段代码正在运行...它是静态的,因此它为不同的对象产生不同的值
  • It shoudn't。即使您使用的是允许这种语法的古老编译器,或者您使用了-fpermissive 编译器标志,它也不会被解析为对srand 的调用。它将定义一个名为srand 的类型为intnew 静态变量,并将使用time(0) 的结果对其进行初始化。 srand 变量将隐藏该函数中标准库中的 srand 函数。所以你根本不会打电话给srand
  • 你更了解先生...我正在使用 Dev c++
  • 我是堆栈新手......所以我不太了解标签以及如何解释......在创建方法中......只需查看上面的代码和静态stand()。 ..如果我使该语句注释程序运行而没有内存错误但输出没有完全产生

标签: c++ c++11 visual-c++ c++14


【解决方案1】:

您的程序正在读取已分配内存的末尾。在您的 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 元素腾出空间应该可以解决问题。

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多