Passing structures of Functions In C

Like an ordinary variable a structure variable can also be passed to a function. We may either pass individual structure elements or the entire structure variable at one go.

In the following three ways a structure can be passed as an argument to a function.

  • 1. by passing an individual structure member
  • 2. by passing entire structure
  • 3. by passing pointer to the structure

passing individual structure members

struct student 
{
    int rollno;
    char name [20];
    char sex;
    int age;
};
struct student stu;
void main ()
{
   . . . . . 
   . . . . .
   stuname (stu. Name, stu. rollno);
   . . . . .
   . . . . .
}
void main ()
{
    printf (“/n/n Inside the function \n”);
    printf (“\nName = %s”, name);
    printf (“\nRoll No = %d”, roll);
}

Passing entire structure

A structure can be passed to a function as an argument. It may consume a lot of stack space (copies whole thing). It is good when function needs copy of the entire structure anyway.


Passing pointer to structure

A structure can be passed to a function as an argument through pointers. It uses less stack area i.e., only passes address of the structure of the function. At the time of calling function address of the structure is passed to the called function. Hence in the called function the argument must be declared as pointer. Generally it is the best way to pass structure as an argument to a function.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext