Structure in c

What is a structure? 
A structure is a key word that create user defined data type in C/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 declare structure variables? 
A structure variable can either be declared with structure declaration or as a separate declaration like basic types. 
 

// A variable declaration with structure declaration.

struct Point
{

   int x, y;

} p1; // The variable p1 is declared with 'Point'
 
 
// A variable declaration like basic data types

struct Point
{

   int x, y;
}; 
 

int main()
{

   struct Point p1; // The variable p1 is declared like a normal variable
}Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.
 

 
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
}; 
The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization. 
struct Point
{

   int x, y;
}; 
 

int main()
{

   // A valid initialization. member x gets value 0 and y

   // gets value 1. The order of declaration is followed.

   struct Point p1 = {0, 1}; 
}
  
 
Posted on by