Search code examples
c++arraysfunctionvariablesfunction-declaration

c++ performing operations on functions and declaring functions


I want to declare a function for the following code which is a matrix that is read from a text file. The code can be seen below.

if (infile == "A.txt")
    {
        ifstream myfile("A.txt");
    string line;
    int MatA[3][3];
    int i=0;
    while (getline (myfile, line))
    {
        stringstream ss(line);
        for(int j=0; j<3; j++)
            ss >> MatA[i][j]; // load the i-th line in the j-th row of mat
        i++;
    }
    // display the loaded matrix                                    
        for(int i=0; i<3; i++)
            {
                for(int j=0; j<3; j++)
            cout<<MatA[i][j]<<" ";
            cout<<endl;
            }

        }

Now what I've tried to do is declare this matrix as a function so when I perform operations later on in my code I can just call the function rather than having to re-write the whole matrix. But I'm having difficulty doing this, the attempt I've made to declare the matrix as a function can be seen below.

int display (int MatA)
{
     for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
           cout<<MatA[i][j]<<" ";
       cout<<endl;
    }
}

However an error occurs saying that [i] 'expression must have a pointer to object type'.

If anybody could help that'd be great!


Solution

  • For example the function can be defined the following way

    const size_t N = 3;
    
    void display( const int ( &MatA )[N][N] )
    {
        for ( size_t i = 0; i < N; i++ )
        {
            for ( size_t j = 0; j < N; j++ ) std::cout << MatA[i][j] << " ";
            std::cout << std::endl;
        }
    }
    

    The other way is the following

    const size_t N = 3;
    
    void display( const int ( *MatA )[N], size_t n )
    {
        for ( size_t i = 0; i < n; i++ )
        {
            for ( size_t j = 0; j < N; j++ ) std::cout << MatA[i][j] << " ";
            std::cout << std::endl;
        }
    }
    

    The functions can be called as

    #include <iostream>
    
    const size_t N = 3;
    
    // the function definitions
    
    int main()
    {
       int a[N][N] = {};
       // some code to fill the matrix
    
       display( a );
       display( a, N );
    }
    

    And at last you can use the approach suggested in comments to the post by @boycy though as for me then I do not like this approach. For example

    #include <iostream>
    
    const size_t N = 3;
    
    void display( const int **MatA, size_t m, size_t n )
    {
        for ( size_t i = 0; i < m * n; i++ )
        {
            std::cout << MatA[i] << " ";
            if ( ( i + 1 ) % n == 0 ) std::cout << std::endl;
        }
    }
    
    int main()
    {
       int a[N][N] = {};
       // some code to fill the matrix
    
       display( reinterpret_cast<const int **>( a ), N, N );
    }