我想有初始化简单网格(2D阵列)与列和行的函数,每个位置(小区)然后结构的大小。
我发现,实现这一在主要功能,但在任何其他功能完成后,通过它运行中途后段错误崩溃它打印网格之前(不像在最后一段)的解决方案。
但是,如果打印网格直接添加初始化部分之后,代码工作正常后,所有故障消失。
我怀疑,主要不现在位置数组被初始化,但我把它当作指针的话,我究竟做错了什么?
下面的代码被划分到两个部分。首先有段错误,第二个没有。唯一的区别是,在第二部分,对于周期用于打印出网格是内部功能初始化的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,一次在主),它打印他们两次,然后冻结,持续10秒和死亡。
在您的CreateMap
功能:
void CreateMap (struct GameGrid *Position, int &Dim_x, int &Dim_y)
{
// ...
Position = new GameGrid[Dim_x * Dim_y];
}
这会修改Position
局部变量而已,它并不改变供应给该参数调用者的价值。
你需要的是重新工作的:
GameGrid *CreateMap(const int Dim_x, const int Dim_y)
{
// ...
return new GameGrid[Dim_x * Dim_y];
}
当返回一个值,你可以捕捉:
int main()
{
int x, y;
cout << "Lets create the game map." << endl;
cout << "Enter number of Columns: ";
cin >> x;
cout << "Enter number of Rows: ";
cin >> y;
GameGrid *Position = CreateMap(x, y);
// ...
}
难道这些功能以外的所有的输入/输出。记住你的SOLID Principles,给该函数一个工作,只有一个作业。输入和分配两个职位。
更妙的是:做一个构造函数,而不是这些CreateX功能。这是C ++,你可以采取的是充分利用。
一如既往:
Whenever you're having strange behaviour, step through your code in a debugger to see what the values of various variables are as it executes.
虽然您使用的是指针作为参数,你仍然传递按值。
当试图指针本身没有改变,但对象传递按引用的地址是指向被更新。
所以更新你需要一个指针的指针或指针引用指针。否则,往往是已经回答了,返回用于返回更新的指针。