Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of passing 2 dimensional array into a function

Tags:

c

I have a 2-dimensional array and I am passing it into a function to carry out certain operations. I'd like to know the correct way of doing it...

#define numRows 3 #define numCols 7 #define TotalNum (numRows*numCols) int arr[numRows][numCols] = {{0,1,2,3,4,5,6}, {7,8,9,10,11,12,13},{14,15,16,17,18,19,20}};  void display(int **p) {     printf("\n");     for (int i = 0; i< numRows;i++)     {         for ( int j = 0;j< numCols;j++)         {             printf("%i\t",p[i][j]);         }         printf("\n");     } }  int main() {     display(arr); } 

I get an error message:

'display': cannot convert parameter1 from 'int' to 'int*' 

Is this the correct way of passing a 2-dimensional array into a function? If not, what is the correct way?

like image 465
lakshmen Avatar asked Feb 25 '12 18:02

lakshmen


People also ask

Can you pass two dimensional array to function in C?

// The following program works only if your compiler is C99 compatible. If compiler is not C99 compatible, then we can use one of the following methods to pass a variable sized 2D array. In this method, we must typecast the 2D array when passing to function.

How do you pass a 2D array to a function in 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. # Use the insert() function to insert the element that contains two parameters.


1 Answers

You should declare your function like this:

void display(int p[][numCols]) 

This C FAQ thoroughly explains why. The gist of it is that arrays decay into pointers once, it doesn't happen recursively. An array of arrays decays into a pointer to an array, not into a pointer to a pointer.

like image 175
cnicutar Avatar answered Sep 23 '22 06:09

cnicutar