【发布时间】:2019-02-05 02:20:07
【问题描述】:
我想要一个函数来初始化带有列和行的简单网格(二维数组),然后每个位置(单元格)就是结构的大小。
我找到了一个解决方案,可以在 main 函数中完成此操作,但在任何其他函数中完成时,在运行到一半后,它在打印 Grid 之前因分段错误而崩溃(与上一段不同)。
但是,如果在初始化部分的后面直接添加打印Grid,之后代码可以正常工作,所有故障都消失了。
我怀疑 main 现在没有初始化 Position 数组,但我将它作为指针传递,我做错了什么?
以下代码分为两部分。第一个有分段错误,第二个没有。唯一不同的是,在第二部分中,用于打印网格的 for 循环在初始化 2d 数组的函数内部。
//SEGMENTATION FAULT
void CreateMap (struct GameGrid *Position, int &Dim_x, int &Dim_y)
{
cout << "Lets create the game map." << endl;
cout << "Enter number of Columns: ";
cin >> Dim_x;
cout << "Enter number of Rows: ";
cin >> Dim_y;
Position = new GameGrid[Dim_x * Dim_y];
}
int main()
{
struct GameGrid *Position = NULL;
int Dim_x;
int Dim_y;
CreateMap(Position, Dim_x, Dim_y);
for (int y=0; y < Dim_y; y++)
{
cout << setw (20);
for (int x=0; x < Dim_x; x++)
{
cout << Position[x*Dim_y + y].Element;
cout << char(32);
}
cout << endl;
}
delete[] Position;
return 0;
}
//NO FAULTS
void CreateMap (struct GameGrid *Position, int &Dim_x, int &Dim_y)
{
cout << "Lets create the game map." << endl;
cout << "Enter number of Columns: ";
cin >> Dim_x;
cout << "Enter number of Rows: ";
cin >> Dim_y;
Position = new GameGrid[Dim_x * Dim_y]
for (int y=0; y < Dim_y; y++)
{
cout << setw (20);
for (int x=0; x < Dim_x; x++)
{
cout << Position[x*Dim_y + y].Element;
cout << char(32);
}
cout << endl;
}
}
int main()
{
struct GameGrid *Position = NULL;
int Dim_x;
int Dim_y;
CreateMap(Position, Dim_x, Dim_y);
delete[] Position;
return 0;
}
对于维度 Dim_x=6 和 Dim_y=6(由最终用户选择),网格应如下所示。
A A A A A A
A A A A A A
A A A A A A
A A A A A A
A A A A A A
A A A A A A
此外,当打印网格两次时(一次在函数 CreateMap 中,一次在 main 中),它会打印两次,然后冻结 10 秒并死掉。
【问题讨论】:
标签: c++ multidimensional-array