简体   繁体   English

分段错误,同时在C中使用rand()生成许多随机数

[英]segmentation fault while generating a number of random numbers using rand() in C

I am writing a program where I need to set a number of elements (specified by the blanks variable) of a 2D array (board) to be 0.(array size is 9x9) These locations has to be picked up in random and once I use the following code segment to do it, the program ends up in a segmentation fault in some instances and does not set the required number of positions to 0. 我正在编写一个程序,需要将2D数组(板)的元素数量(由blanks变量指定)设置为0。(数组大小为9x9)必须随机提取这些位置,使用以下代码段执行此操作,在某些情况下该程序最终会出现段错误,并且未将所需的位置数设置为0。

i = rand() % 10;
j = rand() % 10;

if (board[i][j]){
    board[i][j] = 0;
    blanks--;
}

I have been looking up on this issue bit and came to know that rand() is not thread safe. 我一直在寻找这个问题,并发现rand()不是线程安全的。 Is it the reason for the segmentation fault I am getting, or is it something else? 是我遇到细分错误的原因,还是其他原因?

Further, is there a workaround for this? 此外,是否有解决方法? (For me to get a set of random numbers without this segmentation fault) (对我来说,这是一组随机数,没有这种分段错误)

As per your requirement 根据您的要求

(array size is 9x9) (数组大小为9x9)

your array index should run upto 8 . 您的数组索引应最多运行8 C arrays have 0 based index. C数组具有基于0的索引。

Change 更改

i = rand() % 10;
j = rand() % 10;

to

i = rand() % 9;
j = rand() % 9;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM