我正試圖在課堂上做一些淘氣的事情,並得到了我無法解決的崩潰。我相信這是因爲嘗試讀取未分配的數據而引起的,儘管我認爲應該分配和填充數據。幫幫我..?功能範圍崩潰中的指針
void read(int &n, int &m, double ** arr){
fstream f1;
f1.open("1.txt"); //open a file to read the data from it
f1>>n>>m;
arr = new double *[n];//create an array of pointers (double)
for(int e = 0; e<n; e++){
arr[e] = new double[m]; //assign arrays of doubles to each pointer in the array
for(int l = 0; l < m; l++){
arr[e][l]= 0.f; //set it to 0
}
}
for(int e = 0; e<n; e++){
for(int s = 0; s<m; s++){
f1>>arr[e][s]; //read it from file
}
}
f1.close();
cout<<arr[3][4]<<"\n"; //prints out fine (the last number in my test matrix)
}
int main(){
double ** matrix;
read(n, m, matrix); //fills the matrix
cout<<matrix[0][0]; //crashes the program
return 0;
}
在矩陣中,'matrix'不是'物理地址'嗎?我可以做到這一點,所以我不需要返回任何東西?對不起,如果這是原始的東西,但我想知道什麼是在這裏引擎蓋 – user2468893
讓我編輯我的答案,並添加一些關於「引擎蓋下」的事情 – Awais
我沒有添加細節**內存泄漏* *並正確刪除'矩陣'。好的做法是總是刪除'new'分配的內存以避免內存泄漏。 – Awais