gpt4 book ai didi

c++ - 更改二维矩阵上的值时出现段错误

转载 作者:行者123 更新时间:2023-11-27 22:32:21 26 4
gpt4 key购买 nike

我正在尝试创建随机坐标,但为了确保它们不被使用,我决定创建一个初始化为 0 的二维数组,以显示每个空间都是空的。

我将此函数用于随机性:

int randomNoGenerator(int limit)
{
std::random_device r;

std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(1, limit);
int rand = uniform_dist(e1);
return rand;
}

还有我的主要内容:

int main(void)
{
int numRows = 5;
int numCols = 7;
int **occupiedSpace;

occupiedSpace = (int **)calloc(numRows, sizeof(int *));
for (int i = 0; i < numRows; i++)
occupiedSpace[i] = (int *)calloc(numCols, sizeof(int));

for (int i = 0; i < 5; i++)
{
int x;
int y;
int match = 1;
x = randomNoGenerator(numCols);
y = randomNoGenerator(numRows);

//This is where the crash is happening?
occupiedSpace[x][y] = 1;
}


return 0;
}

我的最终目标是让 where 如果它是空的,它只是用 1 替换它。否则它会继续生成 X,如果它已经被占用,则 Y。

while (match)
{
x = randomNoGenerator(numCols);
y = randomNoGenerator(numRows);
if(occupiedSpace[x][y] = 0)
{
occupiedSpace[x][y] = 1;
match = 0;
}
}

最佳答案

您正在以错误的方式生成您的 xy 坐标。外索引是行,内索引是列,所以你应该这样做:

x = randomNoGenerator(numRows); // instead of numCols
y = randomNoGenerator(numCols); // instead of numRows

然后,您用错误的数字设置了随机生成器。它应该是 uniform_dist(0, limit - 1) 而不是 uniform_dist(1, limit) 因为行和列索引从 0 开始。

关于c++ - 更改二维矩阵上的值时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59395565/

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