简体   繁体   中英

Why am I getting an error when passing this 2D array to a function?

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM