Unit - Iv Structures
Unit - Iv Structures
4.1Structure
Arrays allow to define type of variables that can hold several data items of the same
kind. Similarly structure is another user defined data type available in C that allows to
combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member. The format of the struct statement is as
follows
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it is
optional. Here is the way you would declare the Book structure
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result
Book 1 title : C Programming Book 1
author : Nuha Ali
Book 1 subject : C Programming Tutorial Book 1
book_id : 6495407
Book 2 title : Telecom Billing Book 2
author : Zara Ali
Book 2 subject : Telecom Billing Tutorial Book 2
book_id : 6495700
4.2Nested Structure
When a structure contains another structure, it is called nested structure. For example,we
have two structures named Address and Employee. To make Address nested to Employee,
we have to define Address structure before and outside
Employee structure and create an object of Address structure inside Employee structure.
Syntax for structure within structure or nested structure
struct structure1
{
----------
----------
};
struct structure2
{
----------
80
----------
struct structure1 obj;
};
Example for structure within structure or nested structure
#include<stdio.h> struct
Address
{
char HouseNo[25]; char
City[25];
char PinCode[25];
};
struct Employee
{
int Id;
char Name[25]; float
Salary;
struct Address Add;
};
void main()
{
int i;
struct Employee E;
printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo); printf("\n\tEmployee
City : %s",E.Add.City); printf("\n\tEmployee House No :
%s",E.Add.PinCode);
}
81
Output :
Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi Employee Pin
Code : 110056
4.3Pointer and Structures
Structures can be created and accessed using pointers. A pointer variable of a structure
can be created as below:
int main()
{
struct name *ptr;
}
82
1.Referencing pointer to another address to access the memory
#include <stdio.h> typedef
struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of person1
printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);
return 0;
}
Consider an example to access structure's member through pointer.
In this example, the pointer variable of type struct person is referenced to the address of
person1. Then, only the structure member through pointer can can accessed.
int main()
{
struct person *ptr; int i, num;
83
printf("Enter number of persons: ");
scanf("%d", &num);
return 0;
}
Output
Eve 6
2.3
Displaying Information:
Adam 2 3.20
Eve 6 2.30
4.4Array of Structure
Structure is used to store the information of One particular object but if we need to store such
100 objects then Array of Structure is used.
Example:
struct Bookinfo
{
char[20] bname; int
pages;
int price;
}Book[100];
Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is
used.
3. b1[0] stores the Information of 1st Book , b1[1] stores the information of 2nd Book
and So on We can store the information of 100 books.
84
Example Program For Array Of Structures In C:
This program is used to store and access “id, name and percentage” for 3 students. Structure
array is used in this program to store and display records for many students. You can store “n”
number of students record by declaring structure
variable as „struct student record[n]“, where n can be 1000 or 5000 etc.
Program:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30]; float
percentage;
};
int main()
{
int i;
struct student record[2];
OUTPUT:
Records of STUDENT : 1
Id is:1
Name is:raju
Percentage is:86.5
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is:90.5
85
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.5
Program:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30]; float
percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2 = {2, "Mani", 93.5};
Records of STUDENT 2:
Id is: 2
Name is: Mani
Percentage is: 93.500000
Program:
#include <stdio.h>
#include <string.h>
86
struct student
{
int id;
char name[30]; float
percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id); printf("
Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
OUTPUT:
Records of STUDENT 1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Example Program To Copy A Structure In C:
There are many methods to copy one structure to another structure in C.
1 We can copy using direct assignment of one structure to another structure or
2 we can use C inbuilt function “memcpy()” or we can copy by individual structure
members.
Program:
#include <stdio.h>
#include <string.h> 6.
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2, *record3, *ptr1, record4; 19.
printf("Records of STUDENT1 - record1 structure \n");
printf(" Id : %d \n Name : %s\n Percentage : %f\n",
record1.id, record1.name, record1.percentage);
// 1st method to copy whole structure to another structure
record2=record1;
printf("\nRecords of STUDENT1 - Direct copy from " \"record1 \n");
printf(" Id : %d \n Name : %s\n Percentage : %f\n",record2.id, record2.name,cord2.percentage);
87
// 2nd method to copy using memcpy function
ptr1 = &record1;
memcpy(record3, ptr1, sizeof(record1));
printf("\nRecords of STUDENT1 - copied from record1 " \"using memcpy \n");
printf(" Id : %d \n Name : %s\n Percentage : %f\n",record3->id, record3->name,
record3->percentage);
// 3rd method to copy by individual members
printf("\nRecords of STUDENT1 - Copied individual " \"members from record1 \n");
record4.id=record1.id;
strcpy(record4.name, record1.name);
record4.percentage = record1.percentage;
printf(" Id : %d \n Name : %s\n Percentage : %f\n",record4.id, record4.name,
record4.percentage);
return 0;
}
OUTPUT:
Records of STUDENT1 – record1 structure
Id :1
Name :Raju
Percentage :90.500000
struct NODE
{
struct NODE new; /* 'new' declared variable */ int value;
};
As we know that structure template tells compiler how to allocate storage to its
members and makes computer not to allocate memory to them. When compiler reaches
the line
struct NODE new;
88
template struct NODE is not fully defined. Further, its member „new‟ of type struct NODE
contains a member „new‟ of type struct NODE which in turn contains a member „new‟ again
of type struct NODE and so on indefinitely. In such an instance, compiler can‟t evaluate
correctly how much storage to allocate to „new‟ member of template struct NODE. So we
observed here that a member of struct NODE can‟t be a variable of type struct NODE. Then,
how can we make structure struct NODE self- referential? Let‟s take one more try, this time
we declare a „pointer-to-struct NODE‟
as a member of template struct NODE,
struct NODE {
struct NODE *new; /* 'new' a pointer-to-struct NODE */ int
value;
};
As compiler starts compiling the template struct NODE and reaches line
struct NODE *new;
it finds „new‟, a „pointer-to-struct NODE‟, and also member of struct NODE template, it
evaluates correctly how much bytes of storage to be allocated to „new‟. On linux system,
any pointer type takes 8 bytes of storage. There‟s no problem in using „pointer-to-struct
NODE‟ as a member of struct NODE. Because „new‟ is a „pointer-to-struct NODE‟, structure
struct NODE is called self-referential
structure.
typedef struct NODE {
struct NODE *new;
int value;
}Node;
int main(void)
{
Node previous, current;
89
These limitation are avoided by using dynamic memory allocation in which
memory is more explicitly and more flexibly managed, typically, by allocating it from the
free store(information called the “heap”). In c, the library function malloc is used to allocate a
block of memory via a pointer that the malloc returns.when the memory is no longer needed.
which pointer is passed to other free deallocates the memory so that it can be used for
purposes. some platform provide library calls which allow run time dynamic allocation from
the c stack rather than the heap (eg.alloca() ). This memory is automatically freed when the
calling function ends.
Dynamic memory allocation allows your program to obtain more memory space while
running, or to release it if it's not required. In simple terms, Dynamic memory allocation
allows you to manually handle memory space for your program. In C there are 4 library
functions under "stdlib.h" for dynamic memory allocation.
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated
space
calloc() Allocates space for an array elements, initializes to zero and then returns a
pointer to memory
malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of
type void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
Example:
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block of
memory whereas calloc() allocates multiple blocks of memory each of same size and sets all
bytes to zero.
Syntax of calloc()
90
This statement will allocate contiguous space in memory for an array of n elements.
Example:
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Example: For C malloc() and free()
Sum of Element in an array
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements in the Array: ");
scanf("%d", &num);
Here number of element in the array is read from user at the run time. Array of size n is
allocated in memory using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
Output:
Enter number of elements in the Array: 4
Enter elements of array:7
20
3
5
Sum of Elements in the given array is : 35
Above program also do the same process that was performed in previous program. Only
differens is instead of using malloc() function here calloc() function is used.
92
realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
Syntax of realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, num2,i, *ptr, sum = 0;
94
struct node *first=NULL, *next, *prev, *cur;
Creating the list:
To create the list, we simply allocate memory for a new node, get the data from the user,
assign the newly created node as first and assign NULL as the link part of the node.
void create()
{
cur=(struct node *)malloc(sizeof(struct node));
printf("Enter the data: ");
scanf("%d",&cur->data);
cur->link=NULL;
first=cur;
}
The indirect member access (->) operator is similar to (.) dot operator but accesses the
members of a structure through a pointer. malloc() is used to allocate a block of memory
whose address is stored in cur. cur->link=NULL assigns link part of the node as NULL and
first is made to point to the newly created node.
Displaying contents:
To display each node of the list, we traverse from the first node to the last and display data of
each node. Initially cur is set to point to the first element in the list. Then the data in cur is
printed and cur=cur->link moves cur to the next element. The last step is repeated till cur
becomes NULL (i.e.) after reaching the last element.
void display()
{
cur=first;
printf("Contents of the list: ");
while(cur!=NULL)
{
printf("%d\t",cur->data);
cur=cur->link;
}}
Insertion at beginning:
To insert at first position, memory is allocated to a new node, it is made to link to first and
finally it is made the first node.
void insert_beginning()
{
cur=(struct node *)malloc(sizeof(struct node));
printf("Enter the first element: ");
scanf("%d",&cur->data);
cur->link=first;
first=cur;
95
}
Insertion at end:
To insert at last position, memory is allocated to a new node, its link part is assigned NULL and
the last element is made to point to the newly created node.
void insert_end()
{
cur=(struct node *)malloc(sizeof(struct node));
printf("Enter the last element: ");
scanf("%d",&cur->data);
prev=first;
while(prev->link!=NULL)
prev=prev->link;
cur->link=NULL;
prev->link=cur;
}
prev is made to point to the last element by making it traverse through the list using a while
structure.
void insert_pos()
{
int pos, c=1;
cur=(struct node *)malloc(sizeof(struct node));
printf("Enter the position: "); scanf("%d",&pos);
printf("Enter the data: ");
scanf("%d",&cur->data);
next=first;
while(c<pos)
{
prev=next;
next=prev->link;
c++;
}
if(prev==NULL) printf("\nInvalid
96
position...");
else
{
cur->link=next;
prev->link=cur;
}
}
prev points to cur and cur points to next, in other words, cur is inserted between prev and
next in the required position.
Deletion at beginning:
To delete first element, first is assigned to a temporary variable say cur. Then the second
node, i.e. first->link is assigned as first and then cur is deleted. free() function is used to free
up memory pointed by its argument.
void delete_beginning()
{
cur=first;
first=first->link;
printf("\nDeleted element is %d",cur->data);
free(cur);
}
Deletion at end:
We use while loop to traverse to the node before the last node (prev). prev is assigned
NULL and the last node (cur) is freed.
void delete_end()
{
cur=first;
prev=first;
while(cur->link!=NULL)
{
prev=cur;
cur=cur->link;
}
prev->link=NULL;
printf("\nDeleted element is %d",cur->data); free(cur);
}
Deletion at any position:
The position is read from the user, cur is traversed to the position and prev assigned the node
before cur. Then prev is made to link to the node pointed by cur so that cur is removed from
the list.
97
void delete_pos()
{
int pos, c=1;
printf("Enter the position: ");
scanf("%d",&pos);
cur=first;
prev=first;
while(c<pos)
{
prev=cur;
cur=cur->link;
c++;
}
if(cur==NULL) printf("\nInvalid
position...");
else
{
prev->link=cur->link;
printf("\nDeleted element is %d",cur->data); free(cur);
}
}
Updating value at a position:
To update the data at any particular node, we simply traverse to the required position and
read the new value.
void update()
{
int pos, c=1;
cur=first;
printf("Enter the postion: ");
scanf("%d",&pos);
while(c<pos)
{
cur=cur->link; c++;
}
printf("Enter the new data: ");
scanf("%d",&cur->data);
}
Finding position of a data:
To find the first instance of the data, we traverse each node beginning from first and compare the
data with the search entry.
void find()
{
int c=1, x;
printf("Enter the element to search: ");
98
scanf("%d",&x);
cur=first;
while(cur!=NULL)
{
if(cur->data==x)
{
printf("%d found at position %d",x,c); return;
}
cur=cur->link; c++;
}
printf("%d not found...",x);
}
main() function:
The main() function contains a menu driven switch case statement which calls the corresponding
function based on the choice made by the user.
void main()
{
int i;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Create\n");
printf("2.Display\n");
printf("3.Insert Beginning\n");
printf("4.Insert End\n");
printf("5.Insert Pos\n");
printf("6.Delete Beginning\n");
printf("7.Delete End\n");
printf("8.Delete Pos\n");
printf("9.Update\n");
printf("10.Find\n");
printf("11.Exit\n"); printf("Enter
your choice : "); scanf("%d",&i);
switch(i)
{
case 1: create();
break;
case 2: display();
break;
case 3: insert_beginning();
break;
case 4: insert_end();
break;
case 5: insert_pos();
break;
case 6: delete_beginning();
break;
case 7: delete_end();
break;
99
case 8: delete_pos();
break;
case 9: update();
break;
case 10: find();
break;
case 11: exit(0);
default: printf("Invalid option\n");
}
}
}
Advantages of Singly Linked List.
It is dynamic memory allocation so that there is no wastage of memory.(memory allocated
during run time.)
Simple procedures are used to insert ,delete and to search the element in the list.
Disadvantages of Singly linked list
Extra space is required to store the address of the successor element.
4.9 Typedef
Here type_name represents the stucture definition associated with it. Now
this type_name can be used to declare a variable of this stucture type. type_name t1, t2 ;
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
100
typedef struct student
{
char name[50]; int
mark;
} stud ;
void main( )
{
stud s;
printf("\nEnter Student Detail\n");
printf("\nStudent name\t");
scanf("%s",s.name); printf("\nEnter
Student Mark \t");
scanf("%d",&s.mark);
printf("\nStudent name is: %s",s.name);
printf("\nStudent Mark is: %d",s.mark);
getch();
}
Output:
Enter student detail
Student name raju
Enter student mark 98
IntPtr x, y, z; But if we use typedef like in above example, we can declare any number of
pointers in a single statement.
101