gpt4 book ai didi

c++ - 如何解释动态分配二维数组时有时会发生段错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:03:48 25 4
gpt4 key购买 nike

我想要一个用列和行初始化简单网格(二维数组)的函数,然后每个位置(单元格)都是结构的大小。

我找到了一个在 main 函数中完成这个的解决方案,但是当在任何其他函数中完成时,在运行到一半后它在打印 Grid 之前因段错误而崩溃(与上一段不同)。

但是,如果直接在初始化部分后面添加打印Grid,之后代码可以正常运行,所有错误都消失了。

我怀疑 main 现在 Position 数组已经初始化但我将它作为指针传递,所以我做错了什么?

下面的代码分为两部分。第一个有段错误,第二个没有。唯一的区别是在第二部分中,用于打印网格的 for 循环在初始化二维数组的函数内部。

//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 秒并死掉。

最佳答案

在您的 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.

关于c++ - 如何解释动态分配二维数组时有时会发生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com