所以我现在只是想创建和打印一个整数矩阵。在尝试初始化我的二维整数数组时,我遇到了一个冗长而冗长的 malloc 错误,我不明白问题是什么。我现在只关注创建命令。这是到目前为止的代码:
主.cpp:
using namespace std;
#include "dfs.h"
int main()
{
string temp1;
string temp2;
int n;
int g;
deep d;
do{
cout << "DFS> ";
cin >> temp1;
//Checking for quit command.
if(temp1.compare("quit") == 0)
{
return 0;
}
//Checking for create command.
else if(temp1.compare("create") == 0)
{
cin >> g;
int *array = new int[g];
int s = 0;
while(s < (g*g))
{
cin >> array[s];
s++;
}
d.create(g, array);
}
//Checking for dfs command.
else if(temp1.compare("dfs") == 0)
{
cin >> n;
cout << d.matrix[1][1] << endl;
d.dfs(n);
cout << endl;
}
//Anything else must be an error.
else
{
cout << endl;
cout << "Error! "<< endl;
}
}while(temp1.compare("quit") != 0);
}
dfs.h:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
//DFS class.
class deep{
public:
int max;
int **matrix;
void create(int, int*);
void dfs(int);
//Constructor
deep()
{};
};
dfs.cpp:
#include "dfs.h"
void deep::create(int n, int *array)
{
max = n;
matrix = new int*[max];
for(int i=0; i<max; i++)
{
matrix[i] = new int[max];
}
int c = 0;
for(int j=0; j<n; j++)
{
for(int k=0; k<n; k++)
{
matrix[j][k] = array[c];
c++;
cout << matrix[j][k] << " ";
}
cout << endl;
}
}
void deep::dfs(int u)
{
if(u>=max)
{
cout << "Error! ";
}
else
{
matrix[u][u] = 2;
cout << u;
int v = u+1;
while(u<max && v<max)
{
if(matrix[u][v] != 0 && matrix[u][v] != 2)
{
cout << " ";
dfs(v);
}
}
}
}
重点主要在这里:
void deep::create(int n, int *array)
{
max = n;
matrix = new int*[max];
for(int i=0; i<max; i++)
{
matrix[i] = new int[max];
}
int c = 0;
for(int j=0; j<n; j++)
{
for(int k=0; k<n; k++)
{
matrix[j][k] = array[c];
c++;
cout << matrix[j][k] << " ";
}
cout << endl;
}
}
谢谢您的帮助。