Pages

Wednesday, February 18, 2015

Arrays in C Part 3

Read: Arrays in C - Part 2

So far I told you about some basic topics of arrays in C like initialization of arrays, accepting elements in array, printing the values from an array and so on. Today I will tell you about one advance use of arrays like passing the values of arrays to a function. It can be done in two ways, call by value and call by reference.


Passing Array Elements to a Function

Call by Value

Lets straight away starts with one program.


#include<stdio.h>

void printarr(int);

int main()
{
int x;
int nums[]={43,54,64,56,65};
for(x=0;x<5;x++)
printarr(nums[x]);

return 0;
}

void printarr(int n)
{
printf ("
%d",n) ;
}

Output

Arrays in C - Part 3

Explanation
  • I have declared an integer array nums and inserted 10 elements into it.
  • After that I have started one for loop. Inside the loop I have written one statement i.e. printarr(nums[x]). It will call the function printarr().
  • At first the value of x is 0. Then the first element of nums array will be passed to the printarr() function.
  • That value will be received in the formal argument n of the function. After that it will display the element on the screen with printf() function.
  • Now the control again moves to the main() function. The printarr() function is again called and second element of array nums is passed to it. This process will continue until the loop stops executing. And at last the program will stop.

Call by Reference 

Lets understand it with one program.
#include<stdio.h>

void printarr(int*);

int main()
{
int x;
int nums[]={43,54,64,56,65};

for(x=0;x<5;x++)
printarr(&nums[x]);

return 0;
}

void printarr(int *n)
{
printf("
%d",*n) ;
}

Explanation
  • The code of the program is almost similar to the previous one. But in this case we are passing the address of array elements to the printarr() function.
  • Note that I have passed the address of array elements with the help of address of operator i.e. &.
  • The address of the array element is received by an integer pointer variable n.
  • And in last I have printed the value by using printf() function. The output will be same as previous program.


Which one is better?
As you can see both the approaches are giving the same results. However I need to do little modifications in each program. Remember that the second program is better than the first one. Because it is using the pointer. Usage of pointer decreases the execution time of program. This is the reason people use to prefer pointers while using arrays in C.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.