c Programming 24 25 26
c Programming 24 25 26
Size of structure can be found out using sizeof() operator with structure variable
name or tag name with keyword.
sizeof(struct student); or
sizeof(s1);
sizeof(s2);
Array of structures
#include<stdio.h>
#include<string.h>
struct student
{
char name[30];
char branch[25];
int roll;h
};
void main()
int i;
s[i].roll=i+1;
for(i=0;i<200;i++)
scanf("%s",s[i].name);
scanf("%s",s[i].branch);
printf("\n");
for(i=0;i<200;i++)
puts(s[i].name);
printf("\nBranch:");
puts(s[i].branch);
struct student
char name[30];
int roll,age,marks[5];
Nested structure
struct student
{
element 1;
element 2;
………
………
struct student1
member 1;
member 2;
}variable 1;
……….
……….
element n;
}variable 2;
It is possible to define structure outside & declare its variable inside other
structure.
struct date
int date,month;
};
struct student
{
char nm[20];
int roll;
struct date d;
Nested structure may also be initialized at the time of declaration like in above
example.
{“ram”,201, {12,11}};
struct time
int hr,min;
};
struct day
int date,month;
};
struct student
{
char nm[20];
struct day d;
Lecture Note: 25
We can pass each element of the structure through function but passing individual
element is difficult when number of structure element increases. To overcome this,
we use to pass the whole structure through function instead of passing individual
element.
#include<stdio.h>
#include<string.h>
void main()
struct student
char name[30];
char branch[25];
int roll;
}struct student s;
printf("\nEnter roll:");
scanf("%d",&s.roll);
printf("\nEnter branch:");
gets(s.branch);
display(name,roll,branch);
#include<stdio.h>
#include<string.h>
struct student
char name[30];
int age,roll;
};
void main()
{
display(s1);
display(s2);
display(struct student s)
Output: name=sona
roll=16
Lecture Note: 26
UNION
Union is derived data type contains collection of different data type or dissimilar
elements. All definition declaration of union variable and accessing member is
similar to structure, but instead of keyword struct the keyword union is used, the
main difference between union and structure is
Each member of structure occupy the memory location, but in the unions
members share memory. Union is used for saving memory and concept is useful
when it is not necessary to use all members of union at a time.
Where union offers a memory treated as variable of one type on one occasion
where (struct), it read number of different variables stored at different place of
memory.
Syntax of union:
union student
datatype member1;
datatype member2;
};
Like structure variable, union variable can be declared with definition or separately
such as
Datatype member1;
}var1;
Union members can also be accessed by the dot operator with union variable and if
we have pointer to union then member can be accessed by using (arrow) operator
as with structure.
Example:-
struct
student
struct
student
int i;
char ch[10];
};struct student s;