Structures in C

A structure is a user defined data type in C. A structure creates a data type that can be used to group items of possibly different types into a single type.

How to create a structure?
‘struct’ keyword is used to create a structure. Following is an example.

struct address 

   char name[50]; 

   char street[100]; 

   char city[50]; 

   char state[20]; 

   int pin; 
};
How to initialize structure members?
Structure members cannot be initialized with declaration. For example the following C program fails in compilation.

struct Point 

   int x = 0; // COMPILER ERROR: cannot initialize members here 

   int y = 0; // COMPILER ERROR: cannot initialize members here 
};
#include<stdio.h> 

  

struct Point 

   int x, y; 
}; 

  

int main() 

   struct Point p1 = {0, 1}; 

  

   // Accessing members of point p1 

   p1.x = 20; 

   printf ("x = %d, y = %d", p1.x, p1.y); 

  

   return 0; 
}


How to access structure elements?
Structure members are accessed using dot (.) operator.
Posted on by