Sunday, March 13, 2016

Passing Arrays To Functions

Whenever we need to pass a list of elements as parameter to the function, it is preferred to do that using an array. 
Fundamentally, there is one way to do it. But, syntactically three ways to do it. You can pass entire array to a function using pointer. Usually, pointer variable is used to store memory addresses, so you can pass the location of first element of your array to the function using the pointer.
Usually, when you call a function from your current function then the current function is calledCalling Function and the function you are calling is called Called Function.
When you are passing the array to a function using pointer, you have to pass its size also. Otherwise, if you do some invalid access of array in the called function, it could be a serious problem! So it is best practice to pass the size of array also.
The syntax of the three ways are given below:
Method 1:
<return type> <Function name>(<data type> *<pointer variable name>)
{
/* Your Function Body Here */ ….............................. } Example : int function ( int *my_array, int size) /* size indicating my_array size */ { int i; for (i=0;i<size;i++) printf(“%d ”,my_array[i]); }
Method 2:
<return type> <Function name>(<data type> <pointer variable name>[])
{
 /* Your Function Body Here */
 …..............................
}

Example :
int function ( int my_array[], int size)  /* size indicating my_array size */
{
int i;
for (i=0;i<size;i++)
 printf(“%d ”,my_array[i]);
}
Method 3:
<return type> <Function name>(<data type> <array name>[<array size>])
{
 /* Your Function Body Here */
 …..............................
}

Example :
int function ( int my_array[10])  /* Here 10 indicates my_array size */
{
 int i;
 for (i=0;i<10;i++)
  printf(“%d ”,my_array[i]);
}

You can see that, there is a difference in syntax but all are actually passing the pointer. You can test it by modifying the the values of array in called function and printing the array in callingfunction after calling the called function. You will see that the values has been modified in all the three syntax given above.

No comments: