久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

java - c++ 數據結構這個錯在哪了,動態存儲?

瀏覽:119日期: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:

錯誤的關鍵在這一行:

element[i][j] = x;

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

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

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

回答2:

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

標簽: java
主站蜘蛛池模板: 泾川县| 克拉玛依市| 通海县| 繁昌县| 临夏县| 巴林右旗| 信阳市| 灌阳县| 蒙自县| 琼结县| 比如县| 贵港市| 马鞍山市| 民县| 玛多县| 长岛县| 金昌市| 石狮市| 美姑县| 阿拉善盟| 田东县| 高淳县| 建始县| 扎囊县| 社会| 宝坻区| 顺义区| 调兵山市| 福鼎市| 南靖县| 沧州市| 台东县| 阿克陶县| 新疆| 广安市| 安阳县| 竹北市| 新津县| 凤城市| 历史| 齐齐哈尔市|