Definition
Structure is collection of heterogeneous (different) data types. It is declared by struct keyword. All members of structure by default are public and can be access outside structure by reference variable (structure variable).
Structure elements stored at contiguous memory location. Structure is similar to class except it does not have access specifier (Public, Private, Protected).
For example if we want to collect information of a student (Name, Roll Number, Class etc) than we can group these different type of information into a single unit by structure.
Syntax
struct <structure name>{
element 1;
element 2;
------------
------------
};
};
Declaration of Structure
Structure is declared by struct keyword followed by an identifier i.e. the structure name.for example:
struct Student
Structure body starts with an opening curly braces and ends with closing curly braces. Closing curly braces is followed by a semicolon to end the declaration of structure. for example:
struct Student
{
};
Inside the curly braces of structure we can declare variable along with their data types. for example:
struct Student
{
char Name[25];
int Roll_No;
float Marks;
};
here Student is a structure and Name, Roll_No and Marks are the member variable of structure.
like class, structure is a blueprint for reference variable (structure variable).
When a structure declared it does not occupy space in memory but when we declare it's reference variable (structure variable) that occupy space in memory equal to the sum of size of variables memory present inside structure.
structure is a concept but reference variable (structure variable) is the real representation of structure.
Reference Variable (Structure Variable) Declaration
To declare a reference variable first we will write structure name and after that we will write reference variable name followed by a semicolon. for example:
struct Student stud;
Here Student is the structure name and stud is the reference variable. For reference variable structure works as data type.
In above example stud is a reference variable and Student is the data type for this reference variable and this reference variable can use only those values which are present inside Student structure.
Using Member (Member Variables) of Structure
Member variable of a structure can be access by reference variable using dot (.) operator. For example:
stud .Name="Amir Beg";
stud .Roll_No =1002;
stud .Marks = 89.50f;
stud .Roll_No =1002;
stud .Marks = 89.50f;
Comments
Post a Comment