Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a 2-D array as an argument to function

If I dont know the size of both the dimensions of array and want to print a 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");
    }
    


Compiler gives

error cannot convert ‘int (*)[(((unsigned int)((int)size_B)) + 1)]’ to ‘int ()[]’ for argument ‘1’ to ‘void printAnyMatrix(int ()[], int, int)

like image 950
Anubhav Agarwal Avatar asked Dec 18 '11 09:12

Anubhav Agarwal


People also ask

How do you pass a 2D array into a function in Python?

# Write a program to insert the element into the 2D (two dimensional) array of Python. from array import * # import all package related to the array. arr1 = [[1, 2, 3, 4], [8, 9, 10, 12]] # initialize the array elements. print(arr1) # print the arr1 elements.

How do I pass a 2D dynamic array to a function in CPP?

int **board; board = new int*[boardsize]; for (int i = 0; i < boardsize; i++) board[i] = new int[size]; You need to allocate the second depth of array. Save this answer.

How can you pass an array to a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.


2 Answers

Use template feature 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 deduced in the form of size_A and size_B.

Examples:

int ai[3][9];
printAnyMatrix(ai);
...
double ad[18][18];
printAnyMatrix(ad);
like image 128
iammilind Avatar answered Sep 25 '22 01:09

iammilind


Simplify the signature: a pointer is simpler to read by humans.

You also have an error in the loops: it's less then, not less or equal.

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");
}
like image 31
Adrian Avatar answered Sep 21 '22 01:09

Adrian