Just like a variable, An array can also be passed to a function as an arguments. Passing array can be implemented by two ways:
- Passing array to a function using call by value.
- Passing array to a function using call by reference
In previous, we have learned passing array to a function using call by value. In this tutorial we will learn passing array to a function using function call by reference method.
- Function call by value
- Function call by reference
- Array in C
Before going further in this tutorial, you must be aware with-
Passing array to a function using call by reference:
When we pass address (also known as reference) of variables as an actual arguments while calling a function then this is known as function call by reference. As you know that, In call by reference, the address of the actual parameters is copied into the formal parameters. When we pass an address as an argument, the function declaration should have a pointer as a parameter to receive the passed address.)
Example 1: Passing array to function using call by reference
#include <stdio.h>
#define SIZE 14
void showElements(char*); //Function prototype
void main()
{
char* arr[SIZE]={'w','e','l','c','o','m','e','2','p','r','o','t','e','c'};
for (int i=0; i<SIZE; i++)
{
/* Here we are passing address (Address is also known as reference)
* of each element, this is known as call by reference method.*/
showElements(&arr[i]);
}
}
/*Function definition*/
void showElements(char* c)
{
printf("%c", *c);
}
Output:
w e l c o m e 2 p r o t e c
Example 2: Passing array to function using call by reference
More on this to be updated soon....
/*Program to find sum of array elements using call by reference */
#include <stdio.h>
int arrsum(int*); //Function Declaration
int main(void)
{
int arr[10], *p=NULL, sum=0;
printf("Enter array elements: ");
/* Since we know that array name itself is equivalent
* to address of 1st element of an array i.e. &arr[0]*/
for(p = arr; p < arr+10; p++)
{
scanf("%d",p);
}
/* Passing array name passes the whole array bcz array name contains
* the address of first element of the array */
sum = arrsum(arr);
printf("Sum = %d\n ",sum);
return 0;
}
int arrsum(int *p) //function definition
{
int *q = NULL, sum=0;
q = p; //store starting address of array in pointer q
while(p<(q+10))
{
sum=sum+*p;
p++;
}
return sum;
}
Output:
Sum = 55
More on this to be updated soon....
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.