java - c++ 数据结构这个错在哪了,动态存储?
怪我咯
怪我咯 2017-04-18 10:53:42
0
2
393

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

///////////头文件
#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;
}
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
大家讲道理

The key to the error is in this line:

element[i][j] = x;

This way of using addressing will try to access element (first address)+i*sizeof(int*)+j*sizeof(int).
It’s better to use it obediently:

int* row = element[i];
row[j] = x;

It is more stable, and we are not afraid that different compilers have different interpretation methods.

迷茫

for (int i = 0;i < columns;i++)
改为
for (int i = 0;i < rows;i++)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!