国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

java - c++ 數(shù)據(jù)結(jié)構(gòu)這個錯在哪了,動態(tài)存儲?

瀏覽:102日期:2024-01-06 14:06:18

問題描述

找了半天了,麻煩幫我看下。

///////////頭文件#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;}

問題解答

回答1:

錯誤的關(guān)鍵在這一行:

element[i][j] = x;

這種尋址的使用方式會嘗試訪問element(首地址)+i*sizeof(int*)+j*sizeof(int)。最好還是乖乖地使用:

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

比較穩(wěn)妥一些,也不怕不同的編譯器有不同的解釋方法。

回答2:

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

標簽: java
主站蜘蛛池模板: 鲁甸县| 朝阳县| 夏津县| 樟树市| 临泉县| 云林县| 关岭| 县级市| 犍为县| 红安县| 宜兰市| 深水埗区| 凤山县| 嫩江县| 读书| 太白县| 荆门市| 周至县| 德安县| 海城市| 简阳市| 南城县| 禹城市| 大竹县| 裕民县| 民乐县| 新竹市| 巴楚县| 施秉县| 胶州市| 龙南县| 明星| 扎兰屯市| 于田县| 开封县| 晋州市| 神农架林区| 满洲里市| 茂名市| 潞西市| 黎川县|