3

I try to fill a two dimensional array which I pass to a function but I can't get it to work. Here is my code:

#define ROW    3
#define COLUMN 3
#define EMPTYFIELD ' '

void fillField( char** data, int row, int column );

int main( void )
{
    // Two dimensional array
    char field[ROW][COLUMN];
    fillField( field, ROW, COLUMN );
    return( 0 );
}

void fillField( char** data, int row, int column )
{
    for( int r = 0; r < row; r++ )
    {
        for( int c = 0; c < column; c++ )
        {
            *data = EMPTYFIELD;
            data++;
        }
    }
}

I get the following errors:

In function ‘int main()’:
main.cpp:11:32: error: cannot convert ‘char (*)[3]’ to ‘char**’ for argument ‘1’ to ‘void fillField(char**, int, int)’
  fillField( field, ROW, COLUMN );
                                ^
main.cpp: In function ‘void fillField(char**, int, int)’:
main.cpp:21:9: error: invalid conversion from ‘char’ to ‘char**’ [-fpermissive]
    data = EMPTYFIELD;
         ^
Makefile:208: recipe for target 'main.o' failed
make: *** [main.o] Error 1

How can I solve this Problem? I would appreciate any help! Thanks in advance.

Valinho
  • 105
  • 1
  • 8
  • Well actually this is C, but I compile it as C++ program, because I can initialise a variable within a for-loop. – Valinho Dec 30 '14 at 10:33
  • Dynamic stack-based arrays are not available in standard C++. – 6502 Dec 30 '14 at 10:34
  • Well,Why not use `-std=c99` option to compile it in `c99` mode which allows declaring variables inside `for` loops? – Spikatrix Dec 30 '14 at 10:35

2 Answers2

0
char **data;

Is a double pointer not a 2D array you should be having something like

void fillField(char data[][3],int row,int column);

because the parameter field that is passed is a 2D array not a pointer.

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • As you use `COLUMN` in type, you may remove `column` parameter. – Jarod42 Dec 30 '14 at 10:41
  • @Jarod42 Sorry didn't get you the error was because of passing a 2D array to a double pointer so I mentioned that in my answer are you saying that the paramter `column` in the prototype is not required ? – Gopi Dec 30 '14 at 10:50
  • Yeah, I tell that column parameter is superfluous. – Jarod42 Dec 30 '14 at 11:03
  • @Jarod42 Yes just kept it there to be in sync with OP's function prototype. I might very well get rid of both the paramters row and column as already they are there in the `#define` and it can be used inside the function – Gopi Dec 30 '14 at 11:04
0

You need to dereference data twice. This will solve your problem:

for( int r = 0; r < row; r++ )
{
    for( int c = 0; c < column; c++ )
    {
        data[r][c] = EMPTYFIELD;
    }
}

However, as other answers say, it's a bad idea to pass a 2-d array using **.

meaning-matters
  • 21,929
  • 10
  • 82
  • 142