Unit Iv
Unit Iv
UNIT - IV
STRUCTURES Structure - Nested structures – Pointer and Structures – Array of
structures – Example Program using structures and pointers – Self referential
structures – Dynamic memory allocation - Singly linked list - typedef
4.1 Structure
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
DefiningaStructure
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;
AccessingStructureMembers
To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name
and the structure member that we wish to access. You would use the
keyword struct to define variables of structure type. The following example shows
how to use a structure in a program −
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
TPGIT/CSE 1
CS8251 Dept of CSE Programming in C
char author[50];
char subject[100];
int book_id;
};
int main( ) {
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* 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.2 Nested 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
TPGIT/CSE 2
CS8251 Dept of CSE Programming in C
struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
struct structure1 obj;
};
#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;
TPGIT/CSE 3
CS8251 Dept of CSE Programming in C
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);
}
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
TPGIT/CSE 4
CS8251 Dept of CSE Programming in C
struct name
{member1
;
member2;
.
.
};
int main()
{
struct name *ptr;
}
Here, the pointer variable of type struct name is created.
Accessing structure's member through pointer
A structure's member can be accesssed through pointer in two ways:
1. Referencing pointer to another address to access memory
2. Using dynamic memory allocation
1. Referencing pointer to another address to access the memory
Consider an example to access structure's member through pointer.
#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;
}
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.
Using -> operator to access structure pointer member
Structure pointer member can also be accessed using -> operator.
TPGIT/CSE 5
CS8251 Dept of CSE Programming in C
int main()
{
struct person *ptr;
int i, num;
printf("Displaying Infromation:\n");
for(i = 0; i < num; ++i)
printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight);
return 0;
}
Output
TPGIT/CSE 6
CS8251 Dept of CSE Programming in C
Eve
6
2.3
Displaying Information:
Adam 2 3.20
Eve 6 2.30
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.
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];
TPGIT/CSE 7
CS8251 Dept of CSE Programming in C
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
TPGIT/CSE 8
CS8251 Dept of CSE Programming in C
return 0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000
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;
TPGIT/CSE 9
CS8251 Dept of CSE Programming in C
return 0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Program:
4. #include <stdio.h>
5. #include <string.h>
6.
7. struct student
8. {
9. int id;
10. char name[30];
11. float percentage;
12. };
13.
14. int main()
15. {
16. int i;
17. struct student record1 = {1, "Raju", 90.5};
18. struct student record2, *record3, *ptr1, record4;
19.
20. printf("Records of STUDENT1 - record1 structure \n");
21. printf(" Id : %d \n Name : %s\n Percentage : %f\n",
22. record1.id, record1.name, record1.percentage);
23.
24. // 1st method to copy whole structure to another structure
25. record2=record1;
26.
27. printf("\nRecords of STUDENT1 - Direct copy from " \
28. "record1 \n");
29. printf(" Id : %d \n Name : %s\n Percentage : %f\n",
30. record2.id, record2.name, record2.percentage);
31.
TPGIT/CSE 10
CS8251 Dept of CSE Programming in C
TPGIT/CSE 11
CS8251 Dept of CSE Programming in C
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;
TPGIT/CSE 12
CS8251 Dept of CSE Programming in C
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.
Allocates space for an array elements, initializes to zero and then returns
calloc()
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".
TPGIT/CSE 13
CS8251 Dept of CSE Programming in C
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()
This statement will allocate contiguous space in memory for an array of n elements.
For example:
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;
TPGIT/CSE 14
CS8251 Dept of CSE Programming in C
Output:
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.
Example: for C calloc() and free()
Sum of Element in an array
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
Output:
TPGIT/CSE 15
CS8251 Dept of CSE Programming in C
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.
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;
ptr = realloc(ptr,num2);
if(ptr == NULL)
TPGIT/CSE 16
CS8251 Dept of CSE Programming in C
{
printf("Error! Unable to allocate memory.");
exit(0);
}
Output:
TPGIT/CSE 17
CS8251 Dept of CSE Programming in C
Structure definition:
The structure contains an integer data and a link (i.e.) a pointer to the same data
structure. The structure pointer first points to the first node. first is declared NULL
to indicate that the list is empty initially. cur is the pointer used for list operations
which can point to any one of the nodes as discussed later.
struct node
{
int data;
struct node *link;
};
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:
TPGIT/CSE 18
CS8251 Dept of CSE Programming in C
void insert_beginning()
{
cur=(struct node *)malloc(sizeof(struct node));
printf("Enter the first element: ");
scanf("%d",&cur->data);
cur->link=first;
first=cur;
}
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.
Insert at any position:
We get the position from the user and traverse through so many places from first.
prev and next point to the nodes between which the new node has to be inserted. If
the position is beyond the size of the list, we display an error message.
TPGIT/CSE 19
CS8251 Dept of CSE Programming in C
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 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);
TPGIT/CSE 20
CS8251 Dept of CSE Programming in C
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.
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
TPGIT/CSE 21
CS8251 Dept of CSE Programming in C
{
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: ");
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()
TPGIT/CSE 22
CS8251 Dept of CSE Programming in C
{
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;
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.)
TPGIT/CSE 23
CS8251 Dept of CSE Programming in C
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
typedef is a keyword used in C language to assign alternative names to existing
types. Its mostly used with user defined data types, when names of data types get
slightly complicated. Following is the general syntax for using typedef,
typedef existing_name alias_name
Lets take an example and see how typedef actually works.
typedef unsigned long ulong;
The above statement define a term ulong for an unsigned long type. Now
this ulong identifier can be used to define unsigned long type variables.
ulong i, j ;
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
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);
TPGIT/CSE 24
CS8251 Dept of CSE Programming in C
getch();
}
Output:
TPGIT/CSE 25