0

I am working on a minesweeper game in a console and would like to know how I can modify an array value using a function?

I have a global char table[10][10]; but it can't be global and I need to change the size to what a user wants when starting the program. Also I need to modify the table value in this function:

int findnearbymines(int row, int col) {
    int mines = 0;

    if(table[row - 1][col] == '*')
        mines++;
    if(table[row + 1][col] == '*')
        mines++;
    if(table[row][col - 1] == '*')
        mines++;
    if(table[row][col + 1] == '*')
        mines++;

    if(table[row - 1][col + 1] == '*')
        mines++;
    if(table[row - 1][col - 1] == '*')
        mines++;
    if(table[row + 1][col + 1] == '*')
        mines++;
    if(table[row + 1][col - 1] == '*')
        mines++;

    return mines;
}
Martin Evans
  • 45,791
  • 17
  • 81
  • 97

1 Answers1

0

If it can't be global then you will have to delcare it in your main function after you have determined the size of the matrix.

Read here: C - reading command line parameters to know how to read parameters from the command line. You'll have to do this before you declare your matrix.

As for your function you will have to pass your matrix as a parameter to your function as such:

int findnearbymines(int row, int col, char** table, int width, int height)

You also need to add checks in each of your if statments to make sure you don't go out of the bounds of the matrix should the player select a tile on the edge of the grid.

Hope this helps! Just ask in the comments if you need further clarification or have more questions.

Community
  • 1
  • 1
theKunz
  • 444
  • 4
  • 12
  • 2
    Be very careful. whether `char **` is the correct type for the `table` parameter depends on how it is declared. It would *not* be the correct type to go with the original global definition. – John Bollinger Oct 31 '16 at 15:20
  • 1
    Moreover, being able to detect some of the boundary cells depends on knowing the dimensions of the grid, and those are not communicated by the function signature you have presented. – John Bollinger Oct 31 '16 at 15:22
  • This answer doesn't address the type and construction of the `table` parameter on the calling side. Note that a VLA (variable length array) is not a good choice. See http://stackoverflow.com/questions/4470950/why-cant-we-use-double-pointer-to-represent-two-dimensional-arrays – Klas Lindbäck Nov 01 '16 at 07:42