Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C -- passing a 2d array as a function argument?

Tags:

c

One can easily define a function that accepts a 1d array argument like this:

int MyFunction( const float arr[] )
{    
    // do something here, then return...

    return 1

}

Although a definition such as: int MyFunction( const float* arr ) would work as well.

How can one define a function that accepts a 2d array argument?

I know that this works: int MyFunction( const float** arr ) -- but, is it possible to use the first variation that uses []?

like image 236
user3262424 Avatar asked Jul 28 '11 17:07

user3262424


People also ask

Can we pass a 2D array in a function in C?

We can pass the 2D array as an argument to the function in C in two ways; by passing the entire array as an argument, or passing the array as a dynamic pointer to the function.

How do you pass a 2D character array to a function in C++?

We can have a pointer to the two-dimensional arrays in C++. We can pass a 2D array to a function by specifying the size of columns of a 2D array. We can also pass a pointer to an array. We can also define a pointer as a pointer to pass in a function.

How do you pass one-dimensional and two-dimensional arrays 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

In C99, you can provide the dimensions of the array before passing it:

 void array_function(int m, int n, float a[m][n])
 {
      for (int i = 0; i < m; i++)
          for (int j = 0; j < n; j++)
              a[i][j] = 0.0;
 }


 void another_function(void)
 {
     float a1[10][20];
     float a2[15][15];
     array_function(10, 20, a1);
     array_function(15, 15, a2);
 }
like image 92
Jonathan Leffler Avatar answered Sep 29 '22 15:09

Jonathan Leffler


when we pass 2D array as a arguments to the functions it's optional to specify left most dimensions.The key point here is when any changes made in functions that changes reflects in calling functions because when we pass 2-D array as a arguments means actually functions receive pointer to 1-D array. And size of that is number of columns . examples

1 - int funct(int (*a) [4]);

here a is pointer to array of integer. we can simply pass like this also

2- void funct(int a[][4]);

as I said earlier left most side is always optional. In first example size of a will be 4 because it's normally just pointer. while size of *a will be 16 because we have 4 column and for each column we have 4 bytes so 4*4 = 16 bytes.

But most preferable way is always use dynamic memory allocations.

I hope u got clear

like image 45
Anup Raj Dubey Avatar answered Sep 29 '22 15:09

Anup Raj Dubey