int main() {
int** a;
int l, h;
cout << "the lenght of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a = new int* [l];
a[l] = new int [h];
//a = new int [l][h];
if (l = h) {
Pn(l,a);
}
}
void Pn(int l,int** a) {
intMatrix(l, l, a);
}
void intMatrix(int l, int h, int** a) {
for (int i = 0; i < h; i ) {
for (int j = 0; j < l; j )
a[i][j] = 0; //the exception error
}
}
這是發生錯誤的代碼的一部分。這是什么錯誤,我該如何解決?也是的,我為“l”和“h”輸入了相同的數字。
uj5u.com熱心網友回復:
您沒有正確分配陣列。
之后a = new int* [l];,您嘗試訪問a[l],這是超出范圍的。
您需要為int[]陣列第二維的每個元素分配一個單獨的元素。
即使您正確地執行了該操作,代碼中也存在其他問題:
泄漏陣列。
if (l = h)使用=賦值運算子,從而賦予的價值h來l,然后比較新的價值l反對0比較l來h,你需要使用==比較運算子。回圈
intMatrix()是向后的。外回圈需要遍歷l,內回圈需要遍歷h,而不是相反。唯一intMatrix()可以正常作業的方法是如果l并且h具有相同的值,您if正在(不正確地)試圖強制。但是用戶不會被強制輸入 2 個相同的值。
話雖如此,嘗試更像這樣的東西:
#include <iostream>
using namespace std;
void Pn(int l, int** a);
void intMatrix(int l, int h, int** a);
int main() {
int** a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a = new int* [l];
for(int i = 0; i < l; i) {
a[i] = new int [h];
}
if (l == h)
Pn(l, a);
else
intMatrix(l, h, a);
for(int i = 0; i < l; i) {
delete[] a[i];
}
delete[] a;
}
void Pn(int l, int** a) {
intMatrix(l, l, a);
}
void intMatrix(int l, int h, int** a) {
for (int i = 0; i < l; i) {
for (int j = 0; j < h; j)
a[i][j] = 0;
}
}
不過,您可能會考慮使用一維連續陣列而不是二維稀疏陣列,例如:
#include <iostream>
using namespace std;
void Pn(int l, int* a);
void intMatrix(int l, int h, int* a);
int main() {
int* a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a = new int [l*h];
if (l == h)
Pn(l, a);
else
intMatrix(l, h, a);
delete[] a;
}
void Pn(int l, int* a) {
intMatrix(l, l, a);
}
void intMatrix(int l, int h, int* a) {
for (int i = 0; i < l; i) {
for (int j = 0; j < h; j)
a[(i*l) j] = 0;
}
}
話雖如此,請考慮使用std::vector而不是new[]手動。例如,對于二維陣列:
#include <iostream>
#include <vector>
using namespace std;
void intMatrix(vector<vector<int>> &a);
int main() {
vector<vector<int>> a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a.resize(l);
for(int i = 0; i < l; i) {
a[i].resize(h);
}
intMatrix(a);
// or simply:
// a.resize(l, vector<int>(h, 0));
}
void intMatrix(vector<vector<int>> &a) {
for (size_t i = 0; i < a.size(); i) {
vector<int> &b = a[i];
for (size_t j = 0; j < b.size(); j)
b[j] = 0;
}
}
或者,對于一維陣列:
#include <iostream>
#include <vector>
using namespace std;
void intMatrix(vector<int> &a);
int main() {
vector<int> a;
int l, h;
cout << "the length of the matrix is= ";
cin >> l;
cout << "the height of the matrix is= ";
cin >> h;
a.resize(l*h);
intMatrix(a);
// or simply:
// a.resize(l*h, 0);
}
void intMatrix(vector<int> &a) {
for (size_t i = 0; i < a.size(); i) {
a[i] = 0;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/405163.html
標籤:
