代碼:-
#include <iostream>
using namespace std;
int main() {
int r,c,*p;
cout<<"Rows : ";
cin>>r;
cout<<"Columns : ";
cin>>c;
p=new int[r*c];
cout<<"\nEnter array elements :"<<endl;
int i,j,k;
for( i=0;i<r;i ){
for( j=0;j<c;j ){
cin>>k;
*(p i*c j)=k;
}
}
cout<<"\nThe array elements are:"<<endl;
for( i=0;i<r;i ){
for( j=0;j<c;j ){
cout<<*p<<" ";
p=p 1;
}
cout<<endl;
}
cout<<endl;
delete[]p;
return 0;
}
輸出:-
輸出
錯誤:-
munmap_chunk(): 無效指標行程以退出代碼 -6 結束。
誰能解釋為什么會出現上述錯誤?
uj5u.com熱心網友回復:
問題發生在程式結束時,當您delete[] p. 在它之前的嵌套 for 回圈中,您正在修改p,因此,當最后嘗試delete[] p時,您會得到未定義的行為。
潛在的修復包括,在列印陣列元素時,以與在第一個 for 回圈中相同的方式訪問指標(或如 Jarod 提到的,使用[i * c j].
或者,您可以使用附加變數。
int *tmp = p;
for( i = 0 ; i < r; i ){
for( j = 0; j < c; j ){
cout << *tmp << " ";
tmp = tmp 1; // tmp; also works
}
cout << endl;
}
cout << endl;
delete[] p;
這樣,p仍然指向原來的地址。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/342875.html
