Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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()%25;
column=rand()%64;
}

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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()%25;
column=rand()%64;

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading