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.
struct [structure tag] { //member variable; //member variable; //............................... //............................... //member variable; } [one or more structure variables];
struct student { char month; int roll_no; float percentage; } st1;
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.
Examplest1.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.
Here the total memory allocated by 'st1' structure variable is sum of the all size of member variable.
The structure elements can be initialized either separately using separate assignment statements or jointly.
Syntaxstructure_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').
Examplestudent 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.
Examplest1=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.
Understanding structures in C is crucial for organizing data effectively. Structures allow you to create user-defined data types by grouping together variables of different types under a single name. These variables, known as members or fields, can hold various types of data such as integers, characters, arrays, or even other structures: Initializing structure elements can be done either separately using separate assignment statements or jointly, where the elements are listed in the order of member variable initialization. When assigning one structure variable to another, each member of the source structure is assigned to the corresponding member of the destination structure. This process ensures that the data integrity is maintained across structures. Structures provide a powerful tool for organizing and manipulating complex data in C programs, enabling efficient management of information in a clear and structured manner.