Home > OS >  Why doesn't rand() function work the second time i call my own function?
Why doesn't rand() function work the second time i call my own function?

Time:12-31

I was planning to make a snake game on CMD by using arrays in C language, i've coded the parts of board creating and the game, it wasnt done totally yet, but i have to create also the snake and the food in the table.

I was trying to debug the program, and i've found out that rand() function doesnt work the second time i use my function, also it crashes when i try to call those functions more than once. I couldn't solve why.

int main()
{

int row,column;
create_snake(row,column,2);
create_snake(row,column,3);
}
void create_snake(int row,int column,int x){

srand(time(NULL));

row=rand()%;
column=rand()d;
}

here is the full code (not fully done yet but it crashes)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int board[25][64];

void create_snake(int,int,int);


int main()
{

int row,column;

for(int i=0;i<25;i  ){   //creating board
        for(int a=0;a<64;a  ){
              if(i == 0 || i == 24){
            board[i][a]=1;
            }else if(a == 0 || a==63){
            board[i][a]=1;
            }else{
                board[i][a]=0;
            }
        }
    }

create_snake(row,column,2); //creating snake



/*for(int i=0;i<25;i  ){
        for(int a=0;a<64;a  ){
        printf("%d",board[i][a]);
}
printf("\n");
}
*/
create_snake(row,column,3); //creating food

}



void create_snake(int row,int column,int x){

srand(time(NULL));

row=rand()%;
column=rand()d;

printf("%d   %d",row,column);
printf("\n");
/*if(board[row][column]==1){
  // create_snake(row,column,x);

}else if(board[row][column]==0){
    board[row][column]=x;

}else{
    //create_snake(row,column,x);
}
*/
}
v

CodePudding user response:

Calling srand() multiple times can cause issues, depending on what you want to achieve. More details here. When using rand(), I personally learned it this way:

rand() % (25   1 - 0)   0;
rand() % (64   1 - 0)   0;

In your function declaration above the main function, write out the variable names, don't just type int.

  • Related