2013-04-25 190 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