pass 2-d arrays with different names to the one function

How can i pass 2-d arrays with different names (but the same structure and data type and size) to a function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using namespace std;

void OutputArray ();
int A[4][2] = {{1, 2} , {3, 4} , { 5, 7} , {8, 1} };
int B[4][2] = {{5, 6} , {7, 8} , { 3, 9} , {2, 2} };

int main ()
{
    
    OutputArray(A[][2]);
    OutputArray(B[][2]);

    system("pause");
    return 0;  
}
  
void OutputArray(int intNumbersArray[][2])
{
    for (int intCounter = 0; intCounter < 4 ; intCounter++)
    {
    cout << outputArray[intCounter][0] << outputArray[intCounter][1] << endl;
    }   
       
}


and consequently have the printed A and B.
Last edited on
You don't write in the square brackets. After declaration, when you write something like A[n][m], the compiler will think you are accessing one of the values.

Just write:
1
2
OutputArray(A);
OutputArray(B);
There are several ways.

1)

1
2
3
4
5
6
7
8
void OutputArray( const int ( &a )[4][2] )
{
    for ( auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }   
}


1
2
OutputArray( A );
OutputArray( B );


2)

1
2
3
4
5
6
7
8
void OutputArray( const int ( *a )[4][2] )
{
    for ( auto &row : *a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }   
}


1
2
OutputArray( &A );
OutputArray( &B );


3)

1
2
3
4
5
6
7
8
void OutputArray( const int a[][2], size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        for ( int x : a[i] ) std::cout << x << ' ';
        std::cout << std::endl;
    }   
}


1
2
OutputArray( A, 4 );
OutputArray( B, 4 );


4)
1
2
3
4
5
6
7
8
void OutputArray( const int **a, size_t n, size_t m )
{
    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j < m; j++ ) std::cout << a[i][j] << ' ';
        std::cout << std::endl;
    }   
}


1
2
OutputArray( reinterpret_cast<const int **>( A ), 4, 2 );
OutputArray( reinterpret_cast<const int **>( B ), 4, 2 );

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <iomanip>
#include <list>
#include <vector>

template < typename SEQUENCE_2D >
void print_seq2d( const SEQUENCE_2D& a, int width = 2 )
{
    for( const auto& row : a )
    {
        for( const auto& v : row ) std::cout << std::setw(width) << v  ;
        std::cout << '\n' ;
    }
    std::cout << "------------\n" ;
}

int main()
{
    int a[][3] = { { 1, 2, 3 }, { 3, 4, 5 }, { 5, 6, 7 }, { 8, 9, 1 } } ;
    short b[][4] = { { 35, 16, 7, 8 } , { 3, 29, 2, 42 }, { 21, 32, 43, 54 } } ;
    std::list< std::vector<long> > c = { { 1, 2, 3 }, { 3, 4 }, { 5 }, { 6, 7 }, { 5, 6, 7, 8 } } ;

    print_seq2d(a) ;
    print_seq2d( b, 3 ) ;
    print_seq2d(c) ;
}

http://ideone.com/Vr9GRu
What about reference?
Topic archived. No new replies allowed.