Structure in C


What is Structure?

Structure is a collection of variables of different data types. Structure is useful for representing logically related information of different data types.

How To Define Structure

Syntax

struct structure_name
{
   datatype variable1;
   datatype variable2;
   ..................
   datatype variableN;
};

Structure can be declared using struct keyword.
Members of the structure must be enclosed between curly brackets and declaration of structure must end with semicolon.

Example

struct Student
{
    int rollno;
    char name[20];
    char city[20];
};
Here,
Student is a structure having three members declared inside it.

Compiler will not allocate any memory space to structure members at the time of delaring structure. 

     
How To Declare Structure Variable

Once structure is declared we can declare variables of type structure.
There are two different methods of declaring structure variables.
Method1: Declare Structure variables at the time of declaring structure.

Syntax
struct structure_name 
{
   datatype variable1;
   datatype variable2;
   ..................
   datatype variableN;
}var1,var2,var3;

In above method structure variables are declared just after the definition of structure.

Example
struct Student
{
    int rollno;
    char name[20];
    char city[20];
}S1,S2,S3;
Method2:
Syntax
struct structure_name Var1,Var2,Var3; 

In above method structure variables are created using struct keyword and structure name.

Example
struct Student S1,S2,S3; 

Memory allocation for the members of the structure is done at the time of declaring structure variables. Memeory is allocated Separately for each structure variables.
Total memory occupied by structure variable depends on the data type of structure members.  

Example
struct Student
{
    int rollno;
    char name[20];
    char city[20];
}S1,S2,S3;
Here,
Member Name Data Type Size in Byte
rollno int 2
name char 20
city char 20
Total Memory Occupied 42

So 42 Bytes of memory is allocated to each structure variables S1, S2 and S3.

How To Access Member of Structure

Data Members of the structure can be accessed using name of structure variable followed by dot (.) operator and then followed by member name.

Syntax
structure_variable_name.member_name;

Example
S1.rollno=1;
S1.name="YESHA";
S1.city="Mehsana";

Download Projects


Download Programs