Ch-15-Structure Union Enumerated Data Types
Ch-15-Structure Union Enumerated Data Types
CHAPTER 15
STRUCTURES
INTRODUCTION
● A structure is same as that of records. It stores related information about an entity.
● Structure is basically a user defined data type that can store related information (even of
different data types) together.
● A structure is declared using the keyword struct followed by a structure name. All the variables
of the structures are declared within the structure. A structure type is defined by using the given
syntax.
● struct struct-name
{ data_type var-name;
data_type var-name;
...
};
struct student
{ int r_no;
char name[20];
char course[20];
float fees;
};
● The structure definition does not allocates any memory. It just gives a template that conveys to
the C compiler how the structure is laid out in memory and gives details of the member names.
Memory is allocated for the structure when we declare a variable of the structure. For ex, we
can define a variable of student by writing
struct student stud1;
TYPEDEF DECLARATIONS
● When we precede a struct name with typedef keyword, then the struct becomes a new type. It
is used to make the construct shorter with more meaningful names for types already defined by
C or for types that you have declared. With a typedef declaration, becomes a synonym for the
type.
● For example, writing
● typedef struct student
● {
● int r_no;
● char name[20];
● char course[20];
● float fees;
● };
● Now that you have preceded the structure’s name with the keyword typedef, the student
becomes a new data type. Therefore, now you can straight away declare variables of this new
data type as you declare variables of type int, float, char, double, etc. to declare a variable of
structure student you will just write,
● student stud1;
INITIALIZATION OF STRUCTURES
● Initializing a structure means assigning some constants to the members of the structure.
● When the user does not explicitly initializes the structure then C automatically does that. For int
and float members, the values are initialized to zero and char and string members are initialized
to the ‘\0’ by default.
● The initializers are enclosed in braces and are separated by commas. Note that initializers
match their corresponding types in the structure definition.
● The general syntax to initialize a structure variable is given as follows.
● struct struct_name
● { data_type member_name1;
● data_type member_name2;
● data_type member_name3;
● .......................................
● }struct_var = {constant1, constant2, constant 3,...};
● OR
● struct struct_name
● { data_type member_name1;
● data_type member_name2;
● data_type member_name3;
● .......................................
● };
● struct struct_name struct_var = {constant1, constant2, ….};
● struct student stud1 = {01, “Rahul”, “BCA”, 45000};
ACCESSING THE MEMBERS OF A STRUCTURE
● Each member of a structure can be used just like a normal variable, but its name will be a
bit longer. A structure member variable is generally accessed using a ‘.’ (dot operator).
● The syntax of accessing a structure a member of a structure is:
struct_var.member_name
● For ex, to assign value to the individual data members of the structure variable Rahul, we
may write,
● 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;
Write a program to read and display information of all the
students in the class.
● #include<stdio.h>
● int main()
● { struct student
● {
● int roll_no;
● char name[80];
● float fees;
● char DOB[80];
● };
● struct student stud[50];
● int n, i;
● printf(“\n Enter the number of students : “);
● scanf(“%d”, &n);
● for(i=0;i<n;i++)
● { printf(“\n Enter the roll number : “);
● scanf(“%d”, &stud[i].roll_no);
● printf(“\n Enter the name : “);
● scanf(“%s”, stud[i].name);
● printf(“\n Enter the fees : “);
● scanf(“%f”, stud[i].fees);
● printf(“\n Enter the DOB : “);
● scanf(“%s”, stud[i].DOB);
● }
● for(i=0;i<n;i++)
● { printf(“\n ********DETAILS OF %dth STUDENT*******”, i+1);
● printf(“\n ROLL No. = %d”, stud[i].roll_no);
● printf(“\n NAME. = %s”, stud[i].name);
● printf(“\n ROLL No. = %f”, stud[i].fees);
● printf(“\n ROLL No. = %s”, stud[i].DOB);
● }
● }
Finding the size of a structure
Simple addition
we will make a list of all data and add the types memory required by each.
For example, let's consider a simple structure of an employee.
Using size of operator
sizeof operator is used to calculate the size of a data type, variable, or an expression. To
use this operator simply write, sizeof (struct_name);
For example, the code given below prints the size of structure employee
Subtracting the Addresses
In this technique, we use an array of structure variables. Then we subtract the
address of first element of next consecutive variable from the address of the first
element of preceding structure variable. For example, the code below finds the size of
structure Employee.
Passing Individual Structure Members to a Function
● To pass any individual member of the structure to a function we must use the direct
selection operator to refer to the individual members for the actual parameters. The called
program does not know if the two variables are ordinary variables or structure members.
● #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);
● }
PASSING A STRUCTURE TO A FUNCTION
● When a structure is passed as an argument, it is passed using call by value method. That is a
copy of each member of the structure is made. No doubt, this is a very inefficient method
especially when the structure is very big or the function is called frequently. Therefore, in such a
situation passing and working with pointers may be more efficient.
● The general syntax for passing a structure to a function and returning a structure can be given
as, struct struct_name func_name(struct struct_name struct_var);
● The code given below passes a structure to the function using call-by-value method.
● #include<stdio.h>
● typedef struct
● {
● int x;
● int y;
● }POINT;
● void display(POINT);
● main()
● {
● POINT p1 = {2, 3};
● display(p1);
● return 0;
● }
● void display( POINT p)
● {
● printf("%d %d", p.x, p.y);
● }
PASSING STRUCTURES THROUGH POINTERS
● C allows to crerate a pointer to a structure. Like in other cases, a pointer to a
structure is never itself a structure, but merely a variable that holds the address of a
structure. The syntax to declare a pointer to a structure can be given as
● struct struct_name
● {
● data_type member_name1;
● data_type member_name2;
● .....................................
● }*ptr;
● OR
● struct struct_name *ptr;
● For our student structure we can declare a pointer variable by writing
● struct student *ptr_stud, stud;
● The next step is to assign the address of stud to the pointer using the address
operator (&). So to assign the address, we will write
● ptr_stud = &stud;
● To access the members of the structure, one way is to write
● /* get the structure, then select a member */
● (*ptr_stud).roll_no;
● An alternative to the above statement can be used by using ‘pointing-to’ operator (->)
as shown below.
● /* the roll_no in the structure ptr_stud points to */
● ptr_stud->roll_no = 01;
Write a program using pointer to structure to initialize the
members in the structure.
● #include<stdio.h>
● struct student
● {
● int r_no;
● char name[20];
● char course[20];
● float fees;
● };
● main()
● { struct student stud1, *ptr_stud1;
● ptr_stud1 = &stud1;
● ptr_stud1->r_no = 01;
● strcpy(ptr_stud1->name, "Rahul");
● strcpy(ptr_stud1->course, "BCA");
● ptr_stud1->fees = 45000;
● printf("\n DETAILS OF STUDENT");
● printf("\n ---------------------------------------------");
● printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
● printf("\n NAME = ", puts(ptr_stud1->name));
● printf("\n COURSE = ", puts(ptr_stud1->course));
● printf("\n FEES = %f", ptr_stud1->fees);
● }
SELF REFERENTIAL STRUCTURES
● 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);
● C=BLACK; // VALID IN C
● C=2; // illegal in C
● C=(enum COLORS)2
COMPARING ENUMERATED TYPES
● C also allows using comparison operators on enumerated data type. Look at the following
statements which illustrate this concept.
● bg_color = (enum COLORS)6;
● if(bg_color == WHITE)
● fore_color = BLUE;
● fore_color = BLUE;
● if(bg_color == fore_color)
● printf("\n NOT VISIBLE");
● Since enumerated types are derived from integer type, they can be used in a switch-case
statement.
● enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}bg_color;
● switch(bg_color)
● {
● case RED:
● case BLUE:
● case GREEN:
● printf("\n It is a primary color");
● break;
● case default:
● printf("\n It is not a primary color");
● break;
● }
INPUT/OUTPUT OPERATIONS ON ENUMERATED TYPES
● Since enumerated types are derived types, they cannot be read or written using formatted I/O
functions available in C. When we read or write an enumerated type, we read/write it as an
integer. The compiler would implicitly do the type conversion as discussed earlier.
● enum COLORS(RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
● enum COLORS c;
● scanf("%d", &c);
● printf("\n Color = %d", c);