S.A.Parkhid
S.A.Parkhid

Reputation: 2870

filling a 2d array random

this code will good for n<20, but for n=40 give me access violation error: this code will fill X and O random.

 int i=0,j=0;
 int x=0,y=0;
 int n=40;
 for(i=0;i<n;i++)
 {
     for(j=0;j<n;j++)
         arr[i][j]='O';
 }

 srand(clock());
 for(i=0;i<n*n;i++)
 {
   x = rand()%n;
   y = rand()%n;
   if(arr[x][y] == 'O') arr[x][y]='X';
 }

Declare:

 arr = (char**)malloc(n);
 for(i=0;i<n;i++)
    arr[i] = (char*)malloc(n);

Upvotes: 0

Views: 662

Answers (4)

Dave
Dave

Reputation: 11162

If n is constant, or your compiler supports C99, you can initalize it as a 1-d, then cast it to a pointer-to array:

int i;
char (*arr)[n] = malloc(n*n);
char *vals = (char*)arr;

for(i=0; i<n*n; i++)
   vals[i] = (rand()%2)?'X':'O';

//now, use arr[y][x] as usual

Upvotes: 0

AusCBloke
AusCBloke

Reputation: 18522

for(i=0;i<n*n;i++)
{
   x = rand()%n;
   y = rand()%n;
   if(arr[x][y] == 'O') arr[x][y]='X';
   ...

n*n? arr only has n elements and arr[0...n-1] each only have n elements. If x or y is >= n, you'll be accessing elements past the end of your array and causing undefined behaviour. In this case your lucky because it causes an access violation.

That, and arr = (char**)malloc(n); should be arr = (char**)malloc(n * sizeof(char*));.

Upvotes: 1

KCH
KCH

Reputation: 2854

change

arr = (char**)malloc(n);

to

arr = (char**)malloc(n*sizeof(char*));

Upvotes: 5

Keith Nicholas
Keith Nicholas

Reputation: 44316

you could do :-

 for(i=0;i<n;i++)
     {
         for(j=0;j<n;j++)
             arr[i][j]= ((rand() % 2) == 0) ? 'O' : 'X';
     }

and make sure your array is n by n. Instead of those multiple mallocs, which will allocate memory from all over the place...

 arr = (char**)malloc( n * n * sizeof(char));

Upvotes: 4

Related Questions