0

When I try to pass the sales array to the function, I get this: error

C2664: 'printArray' : cannot convert parameter 1 from 'int [4][5]' to 'int'

Here's the array and call:

    int sales[4][5], row, column;

    for (row = 0; row < 4; row++)
    {
        for (column = 0; column < 5; column++)
        {
            cin >> sales[row][column];
        }
    }

printArray(sales);

and here's the function:

void printArray(int A[4][5])
{
  for(int R=0;R<4;R++)
  {
     for(int C=0;C<5;C++)
        cout<<setw(10)<<A[R][C];
     cout<<endl;
   }
}

Thanks in advance.

Shiva
  • 18,435
  • 13
  • 75
  • 104
  • Function prototype should be just printArray(int A[][5]) – epx Feb 16 '14 at 05:02
  • http://stackoverflow.com/questions/8767166/passing-2d-array-to-function – Johnny Mopp Feb 16 '14 at 05:03
  • http://stackoverflow.com/questions/8767166/passing-2d-array-to-function Have a look at this – pa1geek Feb 16 '14 at 05:04
  • Make sure the prototype argument is the same on the function definition – mr5 Feb 16 '14 at 05:08
  • Thanks for trying to help. I removed the 4 and read those links. It looks right to me, but I still get the same conversion error. @mr5 Can you elaborate? – user3053293 Feb 16 '14 at 05:28
  • @user3053293 Make sure there are no overloaded function above(before the function `call`). Or try to compile this code first : `void printArray(int arr[4][5]) { } int main() { int arr[4][5]; printArray(arr); }` before we proceed. – mr5 Feb 16 '14 at 05:34
  • @mr5 Thanks! That fixed the error. :) – user3053293 Feb 16 '14 at 05:44
  • @user3053293 Also you should follow `Nipun Talukdar` answer, it is much preferred. – mr5 Feb 16 '14 at 05:46

2 Answers2

2

Try this

void printArray(int A[][5])
{
  for(int R=0;R<4;R++)
  {
     for(int C=0;C<5;C++)
        cout<<setw(10)<<A[R][C];
     cout<<endl;
   }
}

Hope this helps.. :)

EDIT: There are some other way to do it. Thought I share it to you:

You can pass a array of pointers.

void printArray(int *A[4])

You can pass a pointer to pointers.

void printArray(int **A)
Rashad
  • 10,519
  • 4
  • 40
  • 67
0

You should modify the printArray function to something like this:

void printArray(int *A, int row, int col)
{
  for(int R=0;R<row;R++)
  {
     for(int C=0;C<col;C++)
        cout<<A[R * col +  C] << endl;
   }
}

Then you call this function as shown:

  printArray(&sales[0][0], 5, 5);

Note you pass the row and column counts as value to the function

Nipun Talukdar
  • 4,206
  • 4
  • 26
  • 36