Search⌘ K

Passing a Structure to a Function

Explore how to pass structures and their elements to functions in C programming, using both value and reference methods. Understand the use of member access operators like dot and arrow, how to handle entire structures or specific elements, and the distinctions between passing by value and by reference.

Passing structure elements

We can pass elements of a structure either by value or by reference.

Passing structure elements by value

The basic syntax of passing elements of a structure by value is given below:

functionName (structVariable.memberName);

See the code given below!

C
# include <stdio.h>
void display ( char *, int, float ) ;
int main( )
{
struct book
{
char n[ 20 ] ;
int nop ;
float pr ;
} ;
struct book b = { "Basic", 425, 135.00 } ;
// Passing structure elements by value
display ( b.n, b.nop, b.pr ) ;
return 0 ;
}
// Pass by value
void display ( char *n, int pg, float p )
{
printf ( "%s %d %f\n", n, pg, p ) ;
}

A pure call by value is not possible here, since we cannot pass the array, n, by value. It would always be passed by reference. ...