# Problem with rand() (trying to create minesweeper)

• 04-28-2011
monkey20
Problem with rand() (trying to create minesweeper)
Hello is there any problem on how i use rand()? It's strange it doesn't work with q and w (q=n+1. w=m_1) but if in their position i put n and m it works. What's wrong? If you need the function tamplo to check tell me...thnx
Code:

```#include <stdio.h> #include <stdlib.h> void tamplo(int n, int m, int **pa); int main(int argc, char *argv[]) {   int i,j,n,m,o,p,a,b,r1,r2,q,w;   int **pa=NULL;   printf("Dwste tis diastaseis tou paixnidiou n x m\n");   printf("Prosoxh, to tamplo mporei na exei megethos to poly 24x30\n");   scanf("%d%d", &n,&m);   printf("Epilxte to epipedo duskolias tou paixnidiou\n");   printf("Pathste 1 gia eukolo, 2 gia metro, 3 gia duskolo kai 4 gia akatorthoto\n");   scanf("%d", &o);   if(o==1)   {       p=m*n/8;   }   if(o==2)   {       p=m*n/7;   }   if(o==3)   {       p=m*n/6;   }   if(o==4)   {       p=m*n/5;   }      pa=(int**)calloc(n, sizeof(int*)); //desmeush mnhmhs gia dimiourgia 2d pinaka   for(i=0;i<n;i++)   {         pa[i]=(int*)calloc(m, sizeof(int));   }   tamplo(n,m,pa);   printf("dwste tis syntetagmenes tou tetragwnou pou thelete na anoixete\n");   scanf("%d%d", &a,&B);   pa[a-1][b-1]=9;   q=n+1;   w=m+1;   for(i=0;i<p;i++)   {       do       {                              r1=rand()%q;           r2=rand()%w;       }while(r1==a && r2==B);       pa[r1][r2]=1;//to 10 antiprosopevei tis narkes   }   tamplo(n,m,pa);      for(i=0;i<n;i++)   {       free(pa[i]);   }   free(pa);   system("PAUSE");          return 0; }```
• 04-28-2011
Salem
> It's strange it doesn't work with q and w (q=n+1. w=m_1)
That's because such values would be out of range for accessing your array.

If you have
int array[N];

Then valid subscripts are from 0 to N-1

And the result of rand()%N is also in the range 0 to N-1 as well (convenient huh).

> int i,j,n,m,o,p,a,b,r1,r2,q,w;
There is a very old disease called SLID, which is "Single Letter Identifier Disease".
Pick some more meaningful variable names.
i and j are fine for loop indices, but pretty much everything else should be meaningful.

I would variously suggest numberOfMines, difficultyLevel etc.
• 04-28-2011
monkey20
You're right. Thank you so much i was searching for it a couple of hours! :/ Now only the hard part for minesweeper remains...minefinder :S