0

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);
asked Dec 5, 2011 at 22:52
4
  • Why not just randomly set the value to X or O in the first loop? Commented Dec 5, 2011 at 22:55
  • 3
    Can we see your arr declaration too? Commented Dec 5, 2011 at 22:56
  • Man I hate 2D array malloc. I never get it right. My guess is that there's nothing that forces malloc above to keep memory contiguous so it will randomly fail. Commented Dec 5, 2011 at 23:05
  • you can use memory from stack if the array will be small, it's a lot easier. Commented Dec 5, 2011 at 23:06

4 Answers 4

5

change

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

to

arr = (char**)malloc(n*sizeof(char*));
answered Dec 5, 2011 at 23:02
Sign up to request clarification or add additional context in comments.

Comments

4

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));
answered Dec 5, 2011 at 23:01

Comments

1
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*));.

answered Dec 5, 2011 at 23:04

Comments

0

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
answered Dec 5, 2011 at 23:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.