Structures
Structures
C
CHAPTER - 8
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 declaration 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.
• Syntax: typedef existing data_type new data_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,
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;
Write a program using structures to read and display the
information about a student
• #include<stdio.h>
• int main()
• { struct student
• { int roll_no;
• char name[80];
• float fees;
• char DOB[80];
• };
• struct student stud1;
• printf(“\n Enter the roll number : “);
• scanf(“%d”, &stud1.roll_no);
• printf(“\n Enter the name : “);
• scanf(“%s”, stud1.name);
• printf(“\n Enter the fees : “);
• scanf(“%f”, &stud1.fees);
• printf(“\n Enter the DOB : “);
• scanf(“%s”, stud1.DOB);
• printf(“\n ********STUDENT’S DETAILS *******”);
• printf(“\n ROLL No. = %d”, stud1.roll_no);
• printf(“\n NAME. = %s”, stud1.name);
• printf(“\n ROLL No. = %f”, stud1.fees);
• printf(“\n ROLL No. = %s”, stud1.DOB);
• }
NESTED STRUCTURES
• A structure can be placed within another structure. That is, a structure may contain another
structure as its member. Such a structure that contains another structure as its member is
called a nested structure.
typedef struct
{
char first_name[20];
char mid_name[20];
char last_name[20];
}NAME;
typedef struct
{
int dd;
int mm;
int yy;
}DATE;
NESTED STRUCTURES
typedef struct student
{
int r_no;
NAME name;
char course[20];
DATE DOB;
float fees;
};
• #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 =%S ", ptr_stud1->name);
• printf("\n COURSE = %S", ptr_stud1->course);
• printf("\n FEES = %f", ptr_stud1->fees);
• }
SELF REFERENTIAL STRUCTURES
• 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.
DYNAMIC MEMORY ALLOCATION
• The process of allocating memory to the variables during the execution of the
program is known as Dynamic Memory Allocation.
• For example, Whenever we needed an array we had declared a static array of fixed
size,
inr arr[100];
• The above statement will create an array to allocate 100 integers
• But most of the time we may utilize only 10% or 20% of the allotted space.
• To overcome this problem and to utilize the memory efficiently C Language
provides the mechanism of dynamically allocating the memory.
• Dynamic Memory Allocation gives better performance in situations in which we
don’t know memory requirements in advance.
DYNAMIC MEMORY ALLOCATION
Function Description
Malloc():
Syntax: ptr=(cast-type *) malloc(byte-size);
Example: a=(int *) malloc (10*sizeof(int));
Calloc():
Syntax: ptr=(cast-type *) calloc(n, elem-size);
Free():
Syntax: free(ptr);
Realloc():
Syntax: ptr=realloc(ptr, newsize);
DYNAMIC MEMORY ALLOCATION
Write a Program to read and display values of an integer array. Allocate space
dynamically for the array.
#include<stdio.h>
#include<stdlib.h>
main()
{
int i, n, *arr;
printf(“Enter the Number of Elements:”);
scanf(“%d”,&n);
arr=(int *)malloc(n*sizeof(int))
if(arr==NULL)
{
printf(“Memory Allocation Failed”);
exit(0);
}
DYNAMIC MEMORY ALLOCATION
else
{
for(i=0; i<n; i++) //GETTING INPUT
{
scanf(“%d”, &arr[i]);
}
for(i=0; i<n; i++) //DISPLAYING OUTPUT
{
printf(“%d”, arr[i]);
}
}
UNION
• Like structure, a union is a collection of variables of different data types. The only difference between a
structure and a union is that in case of unions, you can only store information in one field at any one
time.
• To better understand union, think of it as a chunk of memory that is used to store variables of different
types. When a new value is assigned to a field, the existing data is replaced with the new data.
• Thus unions are used to save memory. They are useful for applications that involve multiple members,
where values need not be assigned to all the members at any one time.
DECLARING A UNION
• The syntax for declaring a union is same as that of declaring a structure.
• union union-name
• { data_type var-name;
• data_type var-name;
...
};
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.
ACCESSING A MEMBER OF A UNION
• A member of a union can be accessed using the same syntax as that of a structure. To access the fields of
a union, use the dot operator(.). That is the union variable name followed by the dot operator followed
by the member name.
INITIALIZING UNIONS
• It is an error to initialize any other union member except the first member
• A striking difference between a structure and a union is that in case of a union, the field fields share the
same memory space, so fresh data replaces any existing data. Look at the code given below and observe
the difference between a structure and union when their fields are to be initialized.
• #include<stdio.h>
• typedef struct POINT1
• { int x, y;
• };
• typedef union POINT2
• {
• int x;
• int y;
• };
• main()
• { POINT1 P1 = {2,3};
• // POINT2 P2 ={4,5}; Illegeal with union
•
• POINT2 P2;
• P2. x = 4;
• P2.y = 5;
• printf("\n The co-ordinates of P1 are %d and %d", P1.x, P1.y);
• printf("\n The co-ordinates of P2 are %d and %d", P2.x, P2.y);
• return 0;
• }
• OUTPUT
• The co-ordinates of P1 are 2 and 3
• The co-ordinates of P2 are 5 and 5
ARRAYS OF UNION VARIABLES
• Like structures we can also have array of union variables. However, because of the problem of new data
overwriting existing data in the other fields, the program may not display the accurate results.
• #include <stdio.h>
• union POINT
• { int x, y;
• };
• main()
• { int i;
union POINT points[3];
points[0].x = 2; points[0].y = 3;
points[1].x = 4; points[1].y = 5;
points[2].x = 6; points[2].y = 7;
for(i=0;i<3;i++)
printf("\n Co-ordinates of Points[%d] are %d and %d", i, points[i].x, points[i].y);
return 0;
}
OUTPUT
• Co-ordinates of Points[0] are 3 and 3
• Co-ordinates of Points[1] are 5 and 5
• Co-ordinates of Points[2] are 7 and 7
UNIONS INSIDE STRUCTURES
• union can be very useful when declared inside a structure. Consider an example in which you want a field of a structure
to contain a string or an integer, depending on what the user specifies. The following code illustrates such a scenario.
• struct student
• { union
• { char name[20];
• int roll_no;
• };
• int marks;
• };
• main()
• { struct student stud;
• char choice;
• printf("\n You can enter the name or roll number of the student");
• printf("\n Do you want to enter the name? (Yes or No) : ");
• gets(choice);
• if(choice=='y' || choice=='Y')
• { printf("\n Enter the name : ");
gets(stud.name);
• }
• else
• { printf("\n Enter the roll number : ");
scanf("%d", &stud.roll_no);
• }
• printf("\n Enter the marks : ");
• scanf("%d", &stud.marks);
• if(choice=='y' || choice=='Y')
printf("\n Name : %s ", stud.name);
• else
printf("\n Roll Number : %d ", stud.roll_no);
• printf("\n Marks : %d", stud.marks);
• }