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. 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. 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
Method2:struct Student { int rollno; char name[20]; char city[20]; }S1,S2,S3; 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. Example
Here,struct Student { int rollno; char name[20]; char city[20]; }S1,S2,S3;
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"; |
|||||||||||||||