funtions and char matrix errors

I keep getting an error when I try to use a function to do something with a character maxtrix in my main program. Here's an example

void print_board (char board[3][3])
{
just some more code here to print the board
}

main ()
{
char board1[3][3] = {
{ 'x', ' ', ' ' },
{ ' ', 'x', ' ' },
{ ' ', ' ', 'x' }
};

print_board (board1[3][3]);
}

and then here's the error:

In function `int main()':
error: invalid conversion from `char' to `char (*)[3]'
error: initializing argument 1 of `void print_board(char (*)[3])'


I tried it with a string matrix and i still get the same error. I can print the board fine in the main, but that doesn't help. I need to print it in a function.
Does anyone know what I'm doing wrong?
I think you can't pass a multidimentional array as parameter
but you could pass a pointer to char pointer (char **) and two int for the number of rows and columns
try with this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void print_board (char ** board, int rows, int cols)
{
//just some more code here to print the board
}

main ()
{
char board1[3][3] = {
{ 'x', ' ', ' ' },
{ ' ', 'x', ' ' },
{ ' ', ' ', 'x' }
};

print_board (board1, 3, 3);
}


I hope this helps you
Last edited on

You can pass a multidimensional array but have to specify one dimension. You can do it like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

#include <cstdlib>
#include <iostream>

#define MAX_BOARD  3

using namespace std;

void print_board (char board[][3]);

int main(int argc, char *argv[])
{
    
    char board1[3][3] = {
                      { 'x', ' ', ' ' },
                      { ' ', 'x', ' ' },
                      { ' ', ' ', 'x' }
                      };
  print_board( board1);    
    system("PAUSE");
    return EXIT_SUCCESS;
}

void print_board (char board[][3])
{
     int i = 0;
     for( i = 0; i < MAX_BOARD; i++)
     {
        for( int j = 0; j < MAX_BOARD; j++)
        {
          cout << board[i][j];
        }        
        cout << endl;  
     }
}


Topic archived. No new replies allowed.