Friday, July 29, 2016

C Basics - Structures in C

Structures allow combining data items of different kind. Structure is user defined data type or derived data type available in C.

Defining Structure:
Structure is defined using struct element. The format of the struct statement is,

struct [structure tag] {

   member definition;   
   ...
   member definition;
} [one or more structure variables];

Structure tag and variable fields are optional. Member definition is a normal variable definition.

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

Accessing Structure Member:
Member Access Operator(.) is used to access any member of a structure. The member access operator is coded as a period between the structure variable name and the structure member.

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

struct employee {
   char  name[50];
   int   age;
   int   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");
   printf("emp[0].name   : %s\n", emp[0].name);
   printf("emp[0].age    : %d\n", emp[0].age);
   printf("emp[0].emp_id : %d\n", emp[0].emp_id);
   
   printf("Employee 2\n");
   printf("emp[1].name   : %s\n", emp[1].name);
   printf("emp[1].age    : %d\n", emp[1].age);
   printf("emp[1].emp_id : %d\n", emp[1].emp_id);
   
   return 0;
}
The output of the above program would be:

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



Related topics:
Structures and Function Parameters 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