我已经尝试了所有方法,但无法正常工作。出于某种原因,我的代码甚至在执行主函数之前就出现了段错误。我最初认为这意味着堆栈溢出,但我如下所示动态分配了 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
更新::这是 sample.txt 输入文件..
.........X
...XX....X
..........
....X..X..
...X...X..
.......XX.
....XX....
..........
..........
..........
最佳答案
程序不会在 main 之前崩溃,以查看您的输出语句包括和 endl (cout << endl) 或在流上调用 flush (cout.flush()),它崩溃是因为文件读取循环没有t 重置 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];
}
关于c++ - 使用小型二维数组会导致堆栈溢出(main 之前的段错误)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391610/