STRUCTURES
“Structure is a collection of non-homogeneous /
heterogeneous / different data elements that can be grouped together under a
common name”.
Structure Declaration and Definition
Syntax: struct Tag
{
Datatype
Member1;
Datatype
Member2;
-
- -
-
- -
Datatype
Membern;
};
Ø struct
is a keyword used to define structure declaration.
Ø Tag is
name of the structure that follows same rules as a valid identifier.
Ø Members
declared inside the structure declaration are called structure elements (or)
structure members.
Ø Structure
declaration must be ended with a semicolon.
Example: struct Book
{
char BName[50];
int Pages;
float Price;
};
Declaration of the structure
does not reserve any storage space.
Memory is allocated only at the time of defining a structure
variable.
Syntax: struct Tag varname1, varname2, - - -
- - , varnamep;
Example: struct Book B1,B2;
Now, the compiler allocates
memory for B1 and B2 as:
i.e., Memory is allocated
individually for each structure variable as well as individual memory area for
each member of the structure.
We have to create an object
of structure to access its members. Object is a variable of type structure.
Structure members are accessed using the dot operator(.) between structure's
object and structure's member name.
Syntax : struct
struct_name var_name;
Example for creating object
& accessing structure members
#include<stdio.h>
struct employee
{
int Id;
char Name[25];
long Salary;
};
void main()
{
struct employee E;
printf("\nEnter
Employee Id : ");
scanf("%d", &E.Id);
printf("\nEnter
Employee Name : ");
scanf("%s", &E.Name);
printf("\nEnter Employee Salary
: ");
scanf("%ld", &E.Salary);
printf("\n\n Employee
Id : %d", E.Id);
printf("\n Employee
Name : %s", E.Name);
printf("\n Employee Salary
: %ld", E.Salary);
}
No comments:
Post a Comment