Reputation: 532
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.
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. 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)
Upvotes: 0
Views: 834
Reputation: 134276
As per your requirement
(array size is 9x9)
your array index should run upto 8
. C
arrays have 0
based index.
Change
i = rand() % 10;
j = rand() % 10;
to
i = rand() % 9;
j = rand() % 9;
Upvotes: 6