Home > other >  C Memory Game - How do I pass the arrays to the display grid function properly?
C Memory Game - How do I pass the arrays to the display grid function properly?

Time:01-30

I'm making a memory game for my C class that randomly assigns some character values to different parts of a 2D array for the player to match together. I'm struggling a bit trying to make the function to display the playing board. It's supposed to show underscores for "masked" characters/characters set to false in the bool, and then when the player picks which column and row they want to reveal, set it to true to see the actual character. I'm just testing it out right now and it's not working. Any tweaks are appreciated.

Here's the relevant code.

const int ROWS = 4;
const int COLS = 4;
int generate_rand_num(int min, int max);
void display_grid(char grid_array[ROWS][COLS], bool mask_array[ROWS][COLS]);

int main() {
char grid[ROWS][COLS] =
  {{'?','?','?','?'},
  {'?','?','?','?'},
  {'?','?','?','?'},
  {'?','?','?','?'}};

char cards[] = { 'a','a','b','b','c','c','d','d','e','e','f','f','g','g','h','h'};

bool mask[ROWS][COLS] = {false};

// Assigning cards to grid.
for (int n = 0; n < 16; n  ) {
  int i = generate_rand_num(0,4);
  int j = generate_rand_num(0,4);
  grid[i][j] = cards[n];
  if (grid[i][j] = '?') {
    grid[i][j] = cards[n];
  }
}

display_grid(grid[ROWS][COL], mask[ROWS][COL]);

  return 0;
}



// Generates random number between 0 and 3.
int generate_rand_num(int min, int max) {
  srand(time(NULL));
  int number = (rand() % max)   min;
  return number;
}

// Displays the grid.
void display_grid(char grid_array[ROWS][COLS], bool mask_array[ROWS][COLS]) {
  if (mask_array[ROWS][COLS] == false) { // If the mask value comes up as false, display an underscore.
    cout <<"_";
  }

  if (mask_array[ROWS][COLS] == true) { // If the mask value comes up as true, display the character.
    cout << grid_array[i][j];
  }

  }

}

CodePudding user response:

Rather than this (which tries to pass a single char and a single bool):

display_grid(grid[ROWS][COL], mask[ROWS][COL]);

you should call it like this (which passes the two arrays, as you intended, although note that the arguments get passed as pointers; i.e. the entire arrays aren't copied as part of the function call):

display_grid(grid, mask);

CodePudding user response:

display_grid(grid[ROWS][COL], mask[ROWS][COL]);

Calling this is an issue since it will try to pass grid[4][4] and mask[4][4], which will be at indices out of bounds. Try just passing grid and mask without the brackets (simply grid and mask)

  •  Tags:  
  • Related