我正试图在课堂上做一些淘气的事情,并得到了我无法解决的崩溃。我相信这是因为尝试读取未分配的数据而引起的,尽管我认为应该分配和填充数据。帮帮我..?功能范围崩溃中的指针
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