Professional Documents
Culture Documents
Chap 7 Structures
Chap 7 Structures
Chap 7 Structures
Objectives
Explain what a structure is
Create structures
Write programs that use structure variables
Create arrays of structures
Appreciate uses of structures in advanced
programming.
Use typedef to create structures.
Distinguish between structures and unions
You can see that in general you can define a structure using:
struct name
{
list of component variables
};
and you can have as long a list of component variables as you need.
Once defined you can declare as many examples of the new type as
you like using:
struct name list of variables;
For example:
then:
employee.age is an int and:
employee.name is a char array.
employee.age=32;
is a valid assignment to an int and:
employee.name[2] = 'X';
is a valid assignment to an element of the char array.
Notice that the qualified name uses the structure variable name and not the
structure type name.
You can use employee.age or employee.name exactly the way you use
other variables.
For example, you can use scanf(“%d”,&employee.age); OR
gets(employee.name);
1. #include<stdio.h>
2. #define SIZE 40
3. struct student
4. {
5. char name[SIZE];
6. int marks;
7. };
8. main()
9. {
10. struct student mystudent; /* declare mystudent as a student type */
11. printf(“Please enter the name of the student \n”);
12. scanf(“%s”, &mystudent.name);
13. printf(“Enter the marks obtained \n”);
14. scanf(“%d”, &mystudent.marks);
15. printf(“%s got %d “, mystudent.name, mystudent.marks);
16. return 0;
17. }
1. main()
2. {
3. struct student mystudent[MAXSTU];
4. int count;
5. for(count=0; count<MAXSTU; count++){
6. printf(“Enter the name and marks of student %d\
n“, count+1);
7. scanf(“%s”, &mystudent[count].name);
8. scanf(“%d”, &mystudent[count].marks);
9. }
5. }
6. return 0;
7. }
For example,
1. typedef struct
2. {
3. char name[SIZE];
4. int marks;
5. }student; /*Student is a user defined data
type*/
6. student student1,student2;
Thus, unions are used to conserve memory. They are useful for
applications involving multiple members, where values need not be
assigned to all members at a time.
The similarity between structures and unions is that both contain
members whose individual data types may differ from one another.
union tag
{
member 1;
member 2;
…..
member n;
};
Or
union tag
{
member 1;
member 2;
…..
member n;
}variable list;
The 12-character string will require more storage area within the
computer’s memory than the integer quantity.
Therefore a block of memory large enough for the 12-
character string will be allocated to each union variable.
A union may be a member of a structure and a structure may be a
member of a union and may be freely mixed with arrays.
union id{
char color[12];
int size;
};
struct clothes
{
char manufact[20];
float cost;
union id descr;
}shirt,blouse;
struct clothes
{
char manufact[20];
float cost;
union
{
char color[12];
int size;
}descr;
};shirt, blouse;