2013-10-12 143 views
0

我試着寫一個程序,但我得到的分割故障(核心轉儲)運行時。當我把一個定義的數組像array_2d [10] [1],問題就解決了,但我需要爲我的項目做內存分配。這是我的代碼的簡單版本:指針多維數組中

#include <iostream> 
#include <cmath> 
#include <fstream> 
#include <cstdlib> 
#include <string> 
using namespace std; 

class Exam 
{ 
    private: 
     double** array_2d; 
     unsigned int num; 
     unsigned int num1; 
    public: 
     Exam(); 
     void memoryallocation(); 
     void show(); 
}; 

Exam::Exam() 
{ 
    num=10; 
    num1=1; 
} 

void Exam::memoryallocation() 
{ 
    double** array_2d = new double*[num]; 
    for (unsigned int i = 0; i < num ;i++) 
    { 
     array_2d[i] = new double[num1]; 
    } 
} 

void Exam::show() 
{ 
    ifstream file; 
    file.open("fish.txt"); 
    for (unsigned int i = 0; i < num; i++) 
    { 
     for (unsigned int j = 0; j < num1; j++) 
     { 
      file >> array_2d[i][j]; 
      cout<<array_2d[i][j]<<" "; 
     } 
     cout<<endl; 
    } 

    file.close(); 
} 

int main() 
{ 
    Exam E; 
    E.memoryallocation(); 
    E.show(); 
    return 0; 
} 
+0

請舉報您正在使用的語言。 – crafter

回答

1

在函數Exam::memoryallocation()中,您再次聲明array_2d。

void Exam::memoryallocation() 
{ 
    array_2d = new double*[num]; //remove the redeclaration of array_2d 
    for (unsigned int i = 0; i < num ;i++) 
    { 
     array_2d[i] = new double[num1]; 
    } 
}