矩阵的动态分配使程序不响应

Dynamic allocation of matrix makes program not respond

本文关键字:程序 不响应 动态分配      更新时间:2023-10-16

我已经浏览了大部分已经发布的问题,似乎找不到解决方法:<

这是我的问题。我有以下图形类(仅包含相关代码):

class Graph{
    protected:
    int **A;
    int n;
    public:
    Graph(){
        A=NULL; 
        n=0;};
    ~Graph(){
        int i;
        if(n)
        for(i=0;i<n;i++)
            delete [] A[i];
        delete A;
        n=0;};
    // Methods
    friend istream& operator>>(istream&,Graph&);
    friend void operator>>(fstream,Graph&);
    friend ostream& operator<<(ostream&,Graph&);
    friend void operator<<(fstream,Graph&);
    int GetA(int i,int j){
        return A[i][j];}
    int Getn(){
        return n;}
    void Setn(int k){
        n=k;}
    void SetA(int i,int j,int k){
        A[i][j]=k;}
    void AllocA();
};

这是main在得到错误之前所做的:

int main(){
    Graph graphA;
    "input.txt">>graphA;
}

"input.txt"包含:

9
0 1 1 0 0 0 0 0 0
1 0 0 1 1 0 0 0 0
1 0 0 0 0 0 0 1 1
0 1 0 0 0 0 0 0 0
0 1 0 0 0 1 0 0 0
0 0 0 0 1 0 1 0 0
0 0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0

重载(文件)>>好友:

void operator>>(char *fis_in,Graph &graph){
        int k,x;
        ifstream fin(fis_in);
        fin>>k;
        graph.Setn(k);
        graph.AllocA();
        int i,j;
        for(i=0;i<k;i++)
            for(j=0;j<k;j++){
                fin>>x;
                graph.SetA(i,j,x);}
        cls;        // #define cls system("cls"), just for convenience
        cout<<"Done !";
        delay(1);   // Irrelevant, just a 1 second delay
        fin.close();
    }

最后,给出错误的方法,AllocA:

void Graph::AllocA(){
    int i;
    *A = new int[n];
    for(i=0;i<n;i++)
        A[i] = new int[n];}

更明确地说,它被困在*A=new int[n];

我检查了n,它是从文件中读取的,值为9,就像它应该的那样。我还尝试手动将其设置为9,以防。。。我真的不知道问题出在哪里。我以前做过矩阵的动态分配,但从未发生过。。希望帖子可读。

在指针指向某个东西之前,不能取消引用指针。A从未初始化,但您可以执行以下操作:

*A = new int[n];

此(*A)正在取消引用。在取消引用之前,您需要将A设置为指向某个内容。