Structure
Structure
Structure
Sample example:
struct book
char title[10];
int pages;
float price;
};
Structure……
struct tag_name
datatype member1;
datatype member 2;
};
Structure……
{ {
… float price;
… }b1,b2;
}var1,var2;
Structure……
{ {
… };
… struct student s;
};
e.g.
strcpy(b1.title,”BASIC”);
b1.pages=360;
b1.price=172.00;
Sample code:
Structure……
struct book
char title[10];
int pages;
float price;
};
Copying of Structures
#include<stdio.h>
#include<conio.h>
void main()
struct employee
{
Structure……
char name[10];
int age;
float salary;
};
clrscr();
strcpy(e2.name,e1.name);
Structure……
(e2.name,e1.name);
e2.age=e1.age;
e2.salary=e1.salary;
e3=e2;
printf("\n%s\t%d\t%f",e1.name,e1.age,e1.salary);
printf("\n%s\t%d\t%f",e2.name,e2.age,e2.salary);
printf("\n%s\t%d\t%f",e3.name,e3.age,e3.salary);
Structure……
getch();
NOTE: This copying of all structure elements at one go has been possible only
because the structure elements are stored in contiguous memory locations.
Nesting of Structures
One structure can be nested within another structure. Using this facility complex
data types can be created.
#include<stdio.h>
Structure Example
#include<stdio.h>
struct Point{
int x;
int y;
};
int main() {
struct Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
typedef
#include<stdio.h>
struct Point{
int x;
int y;
};
int main() {
struct Point p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
Structure……
#include<conio.h>
void main()
struct employee
char name[10];
struct address
Structure……
char phone[10];
char city[10];
int pin;
}a;
};
clrscr();
printf("\nName-->%s\nPhone-->%s",e.name,e.a.phone);
Structure……
printf("\nCity-->%s\nPincode-->%d",e.a.city,e.a.pin);
getch();
Array of Structures
#include<stdio.h>
#include<conio.h>
void main()
struct marks
int sub1;
int sub2;
Structure……
sub2;
int sub3;
}s[5];
int i;
clrscr();
for(i=0;i<5;i++)
scanf("%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3);
}
printf("\n\n Marks of students:\n");
for(i=0;i<5;i++)
{
printf("\nStudent-%d:",i+1);
printf("%d\t%d\t%d",s[i].sub1,s[i].sub2,s[i].sub3);
}
getch();
}
Structure……
Passing Structures as arguments in Functions
Like an ordinary variable, a structure variable can also be passed to a function. We may either pass individual structure elements or the entire structure variable at
one go.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct record
char name[10];
int rollno;
float percent;
}r;
void main()
clrscr();
Structure……
char name[10];
int rollno;
float percent;
}r;
void main()
clrscr();
Structure……
strcpy(r.name,"Arnav");
r.rollno=20;
r.percent=92.0;
display(r);
getch();
printf("\nSTUDENT RECORD");
Structure……
printf("\nName:");
puts(r.name);
printf("Roll#:%d",r.rollno);
printf("\nPercentage:%f",r.percent);