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

查看:81
本文介绍了java - 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;
}

解决方案

错误的关键在这一行:

element[i][j] = x;

这种寻址的使用方式会尝试访问element(首地址)+i*sizeof(int*)+j*sizeof(int)。
最好还是乖乖地使用:

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

比较稳妥一些,也不怕不同的编译器有不同的解释方法。

这篇关于java - c++ 数据结构这个错在哪了,动态存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆