Structure is a method of packing data of different datatypes.
Syntax:
struct
{
datatype var1;
....
datatype var n;
}
Example:
struct stud
{
int studno;
char studname[20];
char classname[10];
} stud1,stud2;
Structure elements are stored in contiguous memory locations.
Number of bytes occupied in memory is:
int studno : 2bytes.
char studname : 20bytes.
char classname : 20bytes.
Total bytes occupied in memory is: 42 bytes(2+20+20).
Access fields of a structure with the “.” notation.
Example:
stud1.studno=10;
strcpy(stud1.studname,”Ram”);
strcpy(stud1.classname,”First”);
The values of the structure variables can be assigned to another structure variable of the same type using the assignment operator.
Example:
stud1=stud2;
One can be nested within another.
Example:
struct studper
{
float studpercen;
struct stud studinfo;
}studper1;
Example program:
main()
{
struct stud
{
int sno;
char sname[20];
}stud1;
printf(“\nEnter student number:”);
scanf(“%d”,stud1.sno);
printf(“\nEnter student name:”);
scanf(“%s”,stud1.sname);
printf(“\nStudent number:%d”,stud1.sno);
printf(“\nStudent name:%s”,stud1.sname);
}
Output:
Enter student number:1
Enter student name:RAJA
Student number:1
Student name:RAJA
No comments:
Post a Comment