Structure in C Programming

Structures in C are used to group together different data types under one name. They allow you to create your own data types, making it easier to organize and manipulate related data.
Unlike simple data types like int or float, structures can hold multiple pieces of data of different types.

Structure Creation

struct [structure tag]
{
   //member variable;
   //member variable;
   //...............................
   //...............................
   //member variable;
} [one or more structure variables]; 

Example of Structure Creation

struct student
{
   char month;
   int roll_no;
   float percentage; 
} st1;

Referencing Structure Elements

Structures group related data items under a single name. Referencing elements within a structure allows you to access and manipulate that data. dot (.) operator is used to access individual variables (members) within a structure.

Example
st1.name="vikas";
st1.roll_no=198481361;
st1.percentage=76.2;

To access the values, use st1.name for the name and st1.roll_no for the roll number, etc. Below is an example illustrating the memory representation of the structure.

Responsive image

Here the total memory allocated by 'st1' structure variable is sum of the all size of member variable.

Initializing Structure Elements

The structure elements can be initialized either separately using separate assignment statements or jointly.

Syntax
structure_tag structure_variable={elements,elements.....};

Here, the condition is that the elements are written in the order of initialization of the member variables in the structure. For example (this example is based on the previously declared structure 'student').

Example
student st1={"vikas" ,183481361, 76.2};

If we assign one structure variable to another structure variable means let st1 and st2 be the two structure variable. then if we want to assign the st1 to st2 then each member of st1 is assign to st2.

Example
st1=st2;

Note: We are previous assign the value in st1.
if you print the structure variable st2 then it gives the same output like st1.