-3
#include<iostream>
using namespace std;

void print_matrix(int* a, int row, int column)
{
    int i, j;
    for(i=0;i<row;++i)
    {
        cout<<"\n";
        for(j=0;j<column;++j)
        {
            int element= *((a+i*column)+j);
            cout<< element<<" " ;
        }
    }
}

int main()
{
    int row, column;
    row = column=3; 
    column=2;   
    int a[row][column];
    int i, j;
    cout<< "Enter the matrix\n";
    for(i=0;i<row;++i)
    {
        for(j=0;j<column;++j)
        {
            cin>> a[i][j];
        }
    }
    int* r = &a[0][0];
    print_matrix(r, row, column);
    **print_matrix(a, row, column); // error**

    system("pause");
    return 0;
}                                             

the error is -- cannot convert int (*)[((unsigned int)((int)column))]' toint*' for argument 1' tovoid print_matrix(int*, int, int)' Why do i get the error, as i think the base address " a = &a[0][0] ", So i can call directly instead of having declaring a new int*r ?

shift66
  • 11,760
  • 13
  • 50
  • 83
user1916200
  • 45
  • 1
  • 1
  • 3

1 Answers1

0

There are a few errors in your code.

To understand how pointers relate to multidimensional arrays, please refer to How do I use arrays in C++?, particularly multidimensional arrays and arrays of pointers. This will help you to understand what I have changed in your code to make it valid.

#include<iostream>

using namespace std;

template <size_t n>
void print_matrix(int (*a)[n], int row, int column)
{
    int i, j;
    for(i=0;i<row;++i)
    {
        cout<<"\n";
        for(j=0;j<column;++j)
        {
            std::cout << a[i][j] << " " ;
        }
    }
}

int main()
{
    const int row = 3, column = 2;
    int a[row][column];
    int i, j;
    cout<< "Enter the matrix\n";
    for(i=0;i<row;++i)
    {
        for(j=0;j<column;++j)
        {
            cin>> a[i][j];
        }
    }
    print_matrix(a, row, column); 
}                              

Further to this, since you are using C++, you should avoid such static arrays and prefer std::vector (or Boost's matrix!) instead.

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247