Structures
Structures
struct tag_name {
data _type member 1;
data _type member 2;
:
data _type member m;
};
– struct is the required keyword.
– tag is the name of the structure.
– member 1, member 2, … are individual member
declarations.
Contd.
The individual structure elements (logically related data items)
are called members.
Example:
A new data-type
It declares a1, a2, a3 as variables of type struct account.
Each one these variables has four members as specified by the
template.
A Compact Form
It is possible to combine the declaration of the structure with
that of the structure variables:
struct tag {
member 1;
member 2;
:
member m;
} var_1, var_2,…, var_n;
struct {
char name[30];
int roll_number;
int total_marks;
char dob[10];
} a1, a2, a3;
Structure variable Declarations
Like primary variables and arrays, structure variables can also be initialized where they are
declared. The format used is quite similar to that used to initiate arrays.
struct student
{
char name[20];
int roll;
float marks;
} std1 = { "Pritesh",67,78.3 };
Structure Initialization
struct student
{
char name[20];
int roll;
float marks;
} std1 = { "Pritesh",67,78.3 };
struct Student
{
int id;
char name[32];
}S1,S2,S3;
S1.id=1234;
S1.name= “C Programming”;
scanf (“%d %s”, &S2.id, S2.name);
Example
struct Point
{
int x, y;
}; // structure template or definition
int main()
{
struct Point p1; // structure variable declaration
variable
Once a structure has been defined, we can declare an array
of structures.
struct student
{
char name[20];
int roll;
float marks;
};
Arrays of Structures
struct student class[50];
defines an array called class that consists of 50 elements. Each
element is of type struct student.