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 []
?
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.
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.
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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With