Thursday, 13 May 2021

Passing One dimensional array to functions

Like normal variable, an array or array elements can be passed to the function. To process arrays on large programs, we have to able to pass them to functions, we can passing 1D array to function in two different ways.


1. Passing only one element: 

We pass data values i.e individual elements like call by value to function. As long as the array element type matches the function parameter type it can be passed, the function can't tell weather the value it receives comes from an array or a variable or an expression. 

The following example shows how to pass individual array elements to function

void fun( int x);

void main()

{

int a[5]={1,2,3,4,5};

fun(a[3]);

getch();

}

void fun(int x)

{

printf("%d",x);

}

In this example, only one element of the array is passed through the called function. This is done by using index value.

2. Passing element by address:

Similar to ordinary variables, we can pass the address of individual array element by using address operator in front of index expression.

The following example shows how to pass individual array elements to function by address

void fun( int *x);

void main()

{

int a[5]={1,2,3,4,5};

fun(&a[3]);

getch();

}

void fun(int *x)

{

printf("%d",*x);

}


3. Passing entire array:

If you want the function operate on the entire array, we must pass entire array to the called function. In C, we can't pass the entire array by value as an argument to the function. However, entire array can be passed to the function by reference. Since the array name is the reference / address to itself.

 

The following example shows how to pass entire array elements to function

void fun( int x[ ]);

void main()

{

int a[5]={1,2,3,4,5};

fun(a);

getch();

}

void fun(int x[ ])

{
for(int i=0;i<5;i++)

{
printf("%d",x);

}

}

0 comments :

Post a Comment

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

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top