0

所以我现在只是想创建和打印一个整数矩阵。在尝试初始化我的二维整数数组时,我遇到了一个冗长而冗长的 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;
}
}

谢谢您的帮助。

4

1 回答 1

0

这里:

int *array = new int[g];
int s = 0;
while(s < (g*g))
{
    cin >> array[s];
    s++;
}

您正在写超出数组的末尾。如果g为 3,array则只有 3 个元素,索引从 0 到 2,但您一直在写入array[8].

于 2013-04-25T02:45:50.450 回答