2013-04-25 194 views
0

所以我只是试图创建和打印一个矩阵的整数现在。当我尝试初始化我的二维整型数组时,我遇到了一个冗长而罗嗦的malloc错误,但我不明白问题出在哪里。我现在只关注创建命令。 这里是到目前为止的代码:Malloc错误初始化二维数组

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

谢谢你的帮助。

+0

如果您提供报告错误的文件名和行号,这将会很有帮助。 – clark 2013-04-25 02:45:32

回答

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]

+0

哇,我觉得自己很无知。非常感谢你。 – 2013-04-25 02:52:23