The normal method I use to pass one-dimensional array to a function is as follows.
#include <stdio.h>
#define ARRAY_SIZE 5
void function(int *ptr_array, int size)
{
int index;
printf("Destination array contents: ");
for(index=0;index<size;index++)
{
printf("%d ",ptr_array[index]);
}
}
int main()
{
int array[ARRAY_SIZE]={1,2,3,4,5};
function(array,ARRAY_SIZE);
printf("\n");
return 0;
}
I did realize that the function accepting the argument can also follow as void function(int ptr_array[],int size) (or) void function(int ptr_array[5],int size).In this scenario the arguement passed is a int * but received in int []. So the questions are
- It looks to me that compiler must do a cast of the accepted argument in the function.How does the array index impacts on the cast?
- If it was a 2D array’s base address that is passed to the function, what is the correct type for accepting the arguments in
int[][]form
In the context of a function parameter declaration,
T a[]andT a[N]are synonymous withT *a;ais a pointer type, not an array type, regardless of whether you use[]or[N]or*.Chapter and verse:
Why would that be the case? This is why:
In the call to
function, the expressionarrayhas type “5-element array ofint“; by the rule in 6.3.2.1/3, it is converted (“decays”) to an expression of type “pointer toint“, and its value is the address of the first element (&array[0]); this pointer value is what gets passed tofunction.If
arrayhad been declared asint array[5][5], then the expressionarraywould be converted from “5-element array of 5-element array ofint” to “pointer to 5-element array ofint“, orint (*)[5], and your function declaration would look likewhich could also be written as
or
Note that in this case, the size of the outer dimension is not optional; it must be specified so that the compiler knows the size of the type being pointed to.