18 October 2014

Passing a Structure to a Function

  1. A function can accept a structure as a parameter and even it returns a parameter too.
  2. Either the individual structure elements can be passed or the entire structure can be passed.
Here is the example, for passing the entire structure to a function
#include <stdio.h>
#include <conio.h>
//Structure declaration
struct student
{
char name[10];
int no;
};
//Function prototypes
void read(struct student);
struct student display(struct student); //function which takes the entire structure as a parameter and it returns a structure also
int main()
{
    struct student s1,s;
     printf("Enter the details");
    scanf("%s %d",s1.name,&s1.no);
    s=display(s1);  //function call
printf("Name is %s and number is %d",s.name,s.no);
    getch();
}
//Function definition
struct student display(struct student s)
{
return s;
}
Nested Structures
A structure can be declared within another structure.
Example include: for a student structure maintaining the date of birth is tougher within the structure,
to avoid the complexity, dateofbirth can be a separate structure as defined below
struct dateofbirth
{
int date;
int month;
int year;
};
struct student
{
char name[50];
int no;
struct dateofbirth dob;
};
so the structure can be accessed using the following:
s.dob.date, s.dob.month, s.dob.year, and s.name, s.no
Example of Nested Structures

#include <stdio.h>
#include <conio.h>
//declare the structure dateofbirth which holds date,month and year
struct dateofbirth
{
int date;
int month;
int year;
};
//declare another structure student which also includes dateofbirth as a datatype
struct student
{
char name[50];
int no;
struct dateofbirth dob; //from another structure
};
int main()
{
struct student s;
printf("Enter the name number and date of birth (dd/mm/yyyy)");
scanf("%s %d %d/%d/%d",s.name,&s.no,&s.dob.date,&s.dob.month,&s.dob.year);
printf("%s %d %d/%d/%d",s.name,s.no,s.dob.date,s.dob.month,s.dob.year);
getch();
return 0;
}
It is always nice to include nested structures in applications as good readability is provided
for Example: building.concrete.cement.quality

 T S Pradeep Kumar