Malloc错误初始化2D数组

时间:2013-04-25 02:40:44

标签: arrays malloc 2d

所以我现在只想创建并打印一个整数矩阵。在尝试初始化我的二维int数组时,我遇到了长而冗长的malloc错误,我不明白问题是什么。我现在只关注create命令。 这是迄今为止的代码:

main.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;
}
}

感谢您的帮助。

1 个答案:

答案 0 :(得分: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]