0

Possible Duplicate:
How do I pass a reference to a two-dimensional array to a function?

I have the following two dimensional array and I was trying to pass it by reference to a function:

char table_[ROWS][COLUMNS];//ROWS AND COLUMNS are constants

 void op_table_(char table_, int ROWS, int COLUMNS)
   {
       for(int i=0;i<ROWS;i++)
           for(int j=0;j<COLUMNS;j++)
               table_[i][j]=0;
   }

but it is not working

Community
  • 1
  • 1
John
  • 794
  • 2
  • 18
  • 34
  • multidimensional arrays as function parameters have subtle differences between C and C++. You'd have to decide which one you want. – Jens Gustedt Dec 30 '11 at 14:03

1 Answers1

3

Here's an example:

#define ROWS 10
#define COLUMNS 10
char table_[ROWS][COLUMNS];//ROWS AND COLUMNS are constants

void op_table_(char table_[ROWS][COLUMNS], int rows, int columns)
{
   for(int i=0;i<rows;i++)
       for(int j=0;j<columns;j++)
           table_[i][j]=0;
}

int main(int argc, char **argv)
{
op_table_(table_, ROWS, COLUMNS);
}

The rows and columns parameters can obviously be left off and substituted with ROWS and COLUMNS in the function body. To make the function more general you code do something like:

void op_table_(void *table_, int rows, int columns)
{
   for(int i=0;i<rows;i++)
       for(int j=0;j<columns;j++)
           *(((char *)table_) + (columns * i) + j) = -1;
}
Richard Pennington
  • 19,673
  • 4
  • 43
  • 72
  • 1
    I see this quite a bit but don't understand fully what is the advantage in using pointer arithmetic over something like `table_[rows * i + j] = -1;` in the second example. – oakley.aaron Dec 30 '11 at 14:23