c++ 数据结构这个错在哪了,动态存储?

找了半天了,麻烦帮我看下。

///////////头文件
#ifndef POSTMASTER_H_INCLUDED
#define POSTMASTER_H_INCLUDED

#include<iostream>
#include <stdio.h>
#include <tchar.h>
using namespace std;
class Matrix
{
    int rows, columns;
    int **element;

    void init(int rows, int columns);

public:
    
    Matrix(int rows, int columns,int x);
    ~Matrix();

    friend ostream& operator<<(ostream& out, Matrix&);
    

};

#endif // POSTMASTER_H_INCLUDED


////////////////////.cpp
#include "wine.h"

void Matrix::init(int rows, int columns)
{
    element = new int*[rows];
    this->rows = rows;
    this->columns = columns;
    for (int i = 0;i < columns;i++)
    {
        element[i] = new int[columns];
    }
}


Matrix::Matrix(int rows, int columns, int x)
{
    this->init(rows, columns);
    cout << "1";
    for (int i = 0;i < rows;i++)
        for (int j = 0;j < columns;j++) 
        {
            element[i][j]=x;                 ///这里貌似出错了?
        }

}

Matrix::~Matrix()
{
    for (int i = 0;i < rows;i++)
    {
        delete element[i];            //delete[] element[i];  ?
    }
    delete element;
}

ostream& operator<<(ostream& os, Matrix&a)
{
    os<< "矩阵(" << a.rows << "," << a.columns << "):" << endl;
    for (int i = 0;i < a.rows;i++)
    {
        os<< endl;
        for (int j = 0;j < a.columns;j++)
            os << a.element[i][j]<<"   ";
    }
    return os;

}


//////////////////main()
#include "wine.h"
#include "wine.cpp"
#include<iostream>
#include<cstdlib>
using namespace std;

int main()
{
    int b[3][2] = { 1,2,3,4,5,6 };

    Matrix a(3,2,4);
    cout << a;

    system("PAUSE");
    return 0;
}
子衿沉夜
浏览 400回答 2
2回答

森林海

错误的关键在这一行: element[i][j] = x; 这种寻址的使用方式会尝试访问element(首地址)+i*sizeof(int*)+j*sizeof(int)。最好还是乖乖地使用: int* row = element[i]; row[j] = x; 比较稳妥一些,也不怕不同的编译器有不同的解释方法。

慕森卡

for (int i = 0;i < columns;i++)改为for (int i = 0;i < rows;i++)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java