Chapter 15 Structure, Union, and Enumerated Data Type
Chapter 15 Structure, Union, and Enumerated Data Type
Fundamentals and
Programming in C
2nd Edition
Reema Thareja
1
© Oxford University Press 2016. All rights reserved.
CHAPTER 15
STRUCTUR
ES
stud1.r_no = 01;
strcpy(stud1.name, “Rahul”);
stud1.course = “BCA”;
stud1.fees = 45000;
• We can assign a structure to another structure of the same type. For ex, if we have two structure
variables stu1 and stud2 of type struct student given as
• struct student stud1 = {01, "Rahul", "BCA", 45000};
• struct student stud2;
• Then to assign one structure variable to another we will write,
• stud2 = stud1;
• The general syntax for declaring an array of structure can be given as,
• struct struct_name struct_var[index];
• struct student stud[30];
• Now, to assign values to the ith student of the class, we will write,
• stud[i].r_no = 09;
• stud[i].name = “RASHI”;
• stud[i].course = “MCA”;
• stud[i].fees = 60000;
• #include<stdio.h>
• typedef struct
• {
• int x;
• int y;
• }POINT;
• void display(int, int);
• main()
• {
• POINT p1 = {2, 3};
• display(p1.x, p1.y);
• return 0;
• }
• void display( int a, int b)
• {
• printf("%d %d", a, b);
• }
• Self referential structures are those structures that contain a reference to data of its same type. That is, a
self referential structure in addition to other data contains a pointer to a data that is of the same type as
that of the structure. For example, consider the structure node given below.
• struct node
• {
• int val;
• struct node *next;
• };
• Here the structure node will contain two types of data- an integer val and next that is a pointer to a
node. You must be wondering why do we need such a structure? Actually, self-referential structure is the
foundation of other data structures.
Again, the typedef keyword can be used to simplify the declaration of union variables.
• The most important thing to remember about a union is that the size of an union is the size of its largest field. This is
because a sufficient number of bytes must be reserved to store the largest sized field.
• Enumerated types can be implicitly or explicitly cast. For ex, the compiler can implicitly cast an
enumerated type to an integer when required.
• However, when we implicitly cast an integer to an enumerated type, the compiler will either generate an
error or warning message.
• To understand this, answer one question. If we write:
• enum COLORS{RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
• enum COLORS c;c = BLACK + WHITE;
• Here, c is an enumerate data type variable. If we write, c = BLACK + WHITE, then logically, it should be 2
+ 6 = 8; which is basically a value of type int. However, the left hand side of the assignment operator is of
the type enum COLORS. SO the statement would complain an error.
• To remove the error, you can do either of two things. First, declare c to be an int.
• Second, cast the right hand side in the following manner. :
• c = enum COLORS(BLACK + WHITE);