[英]Segmentation Fault in dynamically array creation
我正在制作一個 cpp 程序,它從用戶那里獲取兩個輸入,確定二維數組的大小,並將值傳遞給mat類構造函數,並動態創建用戶定義大小的數組。 但是,我不知道為什么它不起作用並顯示分段錯誤
#include<iostream>
using namespace std;
class mat{
int **a;
int r, c;
public:
mat(int row, int col){
r = row;
c = col;
for(int i = 0; i < r; i++){
*a = new int[r];
*a++;
}
}
void input(){
for(int i = 0; i < r; i++){
for(int j = 0; i < c; j++){
cin >> a[i][j];
}
}
}
void display(){
for(int i = 0; i < r; i++){
for(int j = 0; i < c; j++){
cout << a[i][j] << "\t";
}
cout << endl;
}
}
};
int main()
{
int r, c;
cout << "enter row :";
cin >> r;
cout << "enter column :";
cin >> c;
mat m(r, c);
m.input();
cout << "array \n";
m.display();
}
我能感覺到問題出在構造函數中的 for 循環上,或者我做錯了。
該類包含多個錯誤。
a
永遠不會被初始化。 當我們嘗試尋址a
指向的內存時,我們會遇到分段錯誤。 我們可以像這樣初始化它a = new int*[r]
a
點的位置,所以不要使用a++
。 否則a[i][j]
將不會引用第 i 行和第 j 列。 我們還想在某個時候釋放內存。for(int j = 0; i < c; j++)
列的內部循環一旦進入就永遠不會終止,最終會產生分段錯誤。 我們需要將i < c
更改為j < c
。如果我們修復這些錯誤,它看起來像這樣:
class mat {
int** a;
int r, c;
public:
mat(int row, int col) {
r = row;
c = col;
a = new int*[r];
for (int i = 0; i < r; i++) {
a[i] = new int[c];
}
}
void input() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> a[i][j];
}
}
}
void display() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cout << a[i][j] << "\t";
}
cout << endl;
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.