Pass a 2-dimensional array as an argument to the function

If I do not know the size of both sizes of the array and want to print the matrix using the following code
  

    
    void printAnyMatrix(int (*A)[], int size_A, int size_B)
    {
       for (int i = 0; i<=size_A; i++)
       {
           for (int j = 0; j<=size_B; j++)
               printf("%d ", A[i][j]);
           printf("\n");
       }
       printf("\n");
    }
    


The compiler gives

The error cannot convert 'int (*) [((((unsigned int) ((int) size_B)) + 1)] to' int () [] for the argument '1 to' void printAnyMatrix (int () [], int , int)

+5
source share
3 answers

Use the templatefunction for such problems:

template<typename T, unsigned int size_A, unsigned int size_B>
void printAnyMatrix(T  (&Arr)[size_A][size_B])
{       // any type^^  ^^^ pass by reference        
}

Now you can pass any 2D array to this function, and the size will be automatically displayed as size_Aand size_B.

Examples:

int ai[3][9];
printAnyMatrix(ai);
...
double ad[18][18];
printAnyMatrix(ad);
+4
source

Simplify the signature: the index is easier to read by people.

: , .

void printAnyMatrix(int *A, int size_A, int size_B)<br />
{
   for (int i = 0; i<size_A; i++)
   {
       for (int j = 0; j<size_B; j++)
           printf("%d ", A[i*size_B + j]);
       printf("\n");
   }
   printf("\n");
}
+2

, , , . :

template <class T, int size_A, int size_B>
void printAnyMatrix(T (&A)[size_A][size_B])
{
   for (int i = 0; i < size_A; i++)
   {
       for (int j = 0; j < size_B; j++)
           std::cout<<A[i][j]<<' ';
       std::cout<<'\n';
   }
   std::cout<<std::endl;
}

:

template <class T>
void printAnyMatrix(T **A, int size_A, int size_B)
{
   for (int i = 0; i < size_A; i++)
   {
       for (int j = 0; j < size_B; j++)
           cout<<A[i][j]<<' ';
       cout<<'\n';
   }
   std::cout<<std::endl;
}

, , . (: , - )

, cout printf, ++. , printf , .

, , .

+1

All Articles