矩阵的动态分配使程序无响应
Dynamic allocation of matrix makes program not respond
我已经查看了大部分已经 post 的问题,但似乎找不到解决办法:<
这是我的问题。我有以下 class 图表(仅包含相关代码):
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,以防万一...我真的不知道'不知道问题是什么。我以前做过矩阵的动态分配,但这从来没有发生过。希望 post 是可读的。
在指针指向某物之前,您不能解除对指针的引用。 A
从未被初始化,但是你这样做了:
*A = new int[n];
这 (*A
) 正在取消引用。在取消引用之前,您需要设置 A
指向某物。
我已经查看了大部分已经 post 的问题,但似乎找不到解决办法:<
这是我的问题。我有以下 class 图表(仅包含相关代码):
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,以防万一...我真的不知道'不知道问题是什么。我以前做过矩阵的动态分配,但这从来没有发生过。希望 post 是可读的。
在指针指向某物之前,您不能解除对指针的引用。 A
从未被初始化,但是你这样做了:
*A = new int[n];
这 (*A
) 正在取消引用。在取消引用之前,您需要设置 A
指向某物。