我已经尝试了一切,但我无法让它发挥作用。由于某种原因,我的代码甚至在执行main函数之前都是seg faulting。我原本认为这意味着堆栈溢出,但我动态分配了2D数组,如下所示,它仍然是一个问题。他们甚至不是大阵列!只需10x10! 如果您有任何建议,请告诉我。
#include "Recursion.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
Recursion::Recursion(string filename){
//Initaliaze all items in original grid to 0;
grid = new int *[10];
for(int e=0; e<10; e++){
grid[e] = new int[10];
}
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
grid[i][j]= 0;
}
}
ifstream fin(filename);
string line = "";
int x = 0; int y = 0;
while(getline(fin, line)){
for(int i = 0; i < (int)line.length(); i++){
if(line[i] == '.'){
grid[y][x] = 0;
}
else {
grid[y][x] = 1;
}
x++;
}
y++;
}
}
void Recursion::print(){
//Makes a copy of the array.
int **gridCopy;
gridCopy = new int *[10];
for(int e=0; e<10; e++){
grid[e] = new int[10];
}
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
gridCopy[i][j] = grid[i][j];
cout << gridCopy[i][j] << " ";
}
}
int count = 1;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
if(gridCopy[i][j] == 1){
cout << "Group" << count << ": ";
printGroupWith(gridCopy, i, j);
}
}
}
}
void Recursion::printGroupWith(int **arr, int y, int x){
if(y >= 10 || x >= 10){
return;
}
else if(arr[y][x] == 0){
return;
}
else if(arr[y][x] == 1){
arr[y][x] = 0;
cout << "(" << y << ", " << x << ")";
//Checks to the North
if(y > 0){
printGroupWith(arr, y - 1, x);
}
//Checks to the South
if(y < 9){
printGroupWith(arr, y + 1, x);
}
//Checks to the East
if(x < 9){
printGroupWith(arr, y, x + 1);
}
//Checks to the West
if(x > 0){
printGroupWith(arr, y, x - 1);
}
}
}
int main(int argc, char * argv[]){
cout << "hey";
if(argc == 2){
cout << "CHECK";
Recursion A(argv[1]);
cout << "CHECK1";
A.print();
cout << "CHECK2";
}
return 0;
}
这是我定义数组的头文件。注意:我最初尝试使用int name [10] [10]分配给堆栈;符号
#ifndef RECURSION_H
#define RECURSION_H
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
using namespace std;
class Recursion{
private:
int **grid;
public:
Recursion(string filename);
void print();
void printGroupWith(int **arr, int y, int x);
};
#endif
UPDATE ::这里是sample.txt输入文件..
.........X
...XX....X
..........
....X..X..
...X...X..
.......XX.
....XX....
..........
..........
..........
答案 0 :(得分:1)
程序在main之前没有崩溃,要查看你的输出语句include和endl(cout&lt;&lt; endl)或者在流上调用flush(cout.flush()),它崩溃了,因为文件读取循环不会重置x:
while (getline(fin, line))
{
x=0;
for (int i = 0; i < (int)line.length(); i++)
{
if (line[i] == '.')
{
grid[y][x] = 0;
}
else
{
grid[y][x] = 1;
}
x++;
}
y++;
}
之后,您在打印数据时会遇到第二次崩溃,因为您要将新分配的数据分配给网格而不是gridCopy:
for (int e = 0; e < 10; e++)
{
gridCopy[e] = new int[10];
}