Friday, July 29, 2016

C Basics - Structures and Function Parameters in C

Structures can be used as function arguments in the same way of any other variable or pointer.

#include <stdio.h>
#include <string.h>

struct employee {
   char  name[50];
   int   age;
   int   emp_id;
} ;

void printempdetails(struct employee emp)
{
   printf("emp.name   : %s\n", emp.name);
   printf("emp.age    : %d\n", emp.age);
   printf("emp.emp_id : %d\n", emp.emp_id);
}
 
int main( ) {

   struct employee emp[2];    
   
   strcpy( emp[0].name, "Bob Wright");
   emp[0].age = 34;
   emp[0].emp_id = 436587;

   strcpy( emp[1].name, "John Ray");
   emp[1].age = 27;
   emp[1].emp_id = 192837;
   
   printf("Employee 1\n");
   printempdetails(emp[0]);
   
   printf("Employee 2\n");
   printempdetails(emp[1]);
   
   return 0;
}
The output of the above program would be:

Employee 1
emp.name   : Bob Wright
emp.age    : 34
emp.emp_id : 436587
Employee 2
emp.name   : John Ray
emp.age    : 27
emp.emp_id : 192837



Related topics:
Structures in C   |   Structures and Pointers in C   |   Structure Bit Fields in C   |   Union in C   |   Enumeration in C   |   Typedef in C

List of topics: C Programming

No comments:

Post a Comment