矩阵的动态分配使程序不响应
Dynamic allocation of matrix makes program not respond
我已经浏览了大部分已经发布的问题,似乎找不到解决方法:<
这是我的问题。我有以下图形类(仅包含相关代码):
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
设置为指向某个内容。
相关文章:
- C++程序不会从 Windows 控制台运行
- 程序不会执行函数 c++
- 为什么我的程序不能显示斐波那契级数?
- C++ 信号和插槽不工作:插槽不响应事件
- 为什么使用数组元素查找最大数字的程序不起作用?
- 程序不向函数返回值
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- C++ 程序不会因为内存而终止
- 为什么一个简单的程序不能立即启动
- OpenGL程序不显示三角形
- 此程序不会打印整个字符串
- 用于拆分空格字符串的程序不起作用
- 反转一个数字程序不起作用,为什么?
- Qt应用程序不响应鼠标和键盘事件
- 前和后条件用法。为什么程序不响应条件
- 矩阵的动态分配使程序不响应
- 快速排序模板不起作用,并使我的程序无响应
- Qt程序挂起(不响应),直到函数结束,然后再次开始工作
- MFC应用程序:动画图形导致程序不响应
- WPF应用程序不响应WM_CLOSE