CS3251 UNIT IV Notes
CS3251 UNIT IV Notes
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 Introduction
Using C language we can create new data types. These data types are known as
User Defined data types & can be created by using Structures, Unions &
Enumerations.
Need for Structure
Arrays can store data of same data type. They can’t be used to store data of
different data types. For this Structures are used.
Structures
A structure is a collection of variables of different types under a single name. It
is used for storing different types of data.
3 aspects:
1. Defining a structure type
2. Declaring variables
3. Using & performing operations.
4.1.1 Structure Definition
The structure can be defined with the keyword struct followed by the name of
structure and opening brace with data elements of different type then closing brace
with semicolon.
General Form
struct [structure tag name]
{
type membername1;
type membername2;
……
}[variable name];
E.g.
struct book
{
char title[25];
int pages;
1
CS3251 Programming in C – UNIT IV
float price;
};
• Structure definition does not reserve any space in the memory.
• It is not possible to initialize the structure members during the structure
definition.
• A structure definition must always be terminated with a semicolon.
2
CS3251 Programming in C – UNIT IV
Example program:
#include<stdio.h>
struct name
{
char fname[20],lastname[20];
};
3
CS3251 Programming in C – UNIT IV
struct student
{
int sno,m1,m2,m3;
int tot;
float avg;
struct name sname;
};
void main()
{
struct student s[10];
float,avg;
int n,i;
printf(“Enter the number of students \n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter student details \n”);
scanf(“%d”,&s[i].sno);
scanf((“%d%d%d”,&s[i].m1, &s[i].m2, &s[i].m3);
scanf(“%s”, s[i].sname.fname);
scanf((“%s”,s[i].sname.lastname);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/6.0;
}
printf(“Student Mark lists\n”);
for(i=0;i<n;i++)
printf(“%s\t%s\t%f”,s[i].sname.fname, s[i].sname.lastname,s[i].avg);
}
Output:
4
CS3251 Programming in C – UNIT IV
E.g) s[i].sname.lastname
student
sn
o
m1
m2
m3
avg
name
fname
lastname
4.3 Pointer and Structures
5
CS3251 Programming in C – UNIT IV
Example:
struct struct_name
{
data_type member_name1;
data_type member_name2;
.....................................
}*ptr;
OR
struct struct_name *ptr;
Dot(.) operator is used to access the data using normal structure variable and arrow
(->) is used to access the data using pointer variable.
6
CS3251 Programming in C – UNIT IV
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of Student: \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:
Id is: 1
Name is: Sankar
Percentage is: 90.500000
7
CS3251 Programming in C – UNIT IV
Using a single structure variable we can store single student details. To store
information about several students, we have to create a separate variable for each
student. It is not feasible. So array of structures are used.
General form
E.g. Program:
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[15];
int empid,bsal;
float net,gross;
};
void main()
{
struct employee emp[10];
float hra,da,tax;
int n,i,j;
clrscr();
printf("Enter the number of employees\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter the employee name");
scanf("%s",emp[i].name);
printf("\nEnter the employee id");
8
CS3251 Programming in C – UNIT IV
scanf("%d",&emp[i].empid);
printf("\nEnter the basic salary");
scanf("%d",&emp[i].bsal);
hra=((10*emp[i].bsal)/100);
da=((35*emp[i].bsal)/100);
tax=((15*emp[i].bsal)/100);
emp[i].gross=emp[i].bsal+hra+da;
emp[i].net=emp[i].gross-tax;
}
printf("Employee Name Employee ID Employee Net Salary \n");
for(i=1;i<=n;i++)
printf("%s\t\t%d\t\t%f\n",emp[i].name,emp[i].empid,emp[i].net);
getch();
}
Output:
Enter the number of Employees
2
Enter the employee name
Anu
Enter the employee id
01
Enter the basic salary
1000
Enter the employee name
Meena
Enter the employee id
02
Enter the basic salary
9
CS3251 Programming in C – UNIT IV
2000
Employee Name Employee ID Net Salary
Anu 01 1300.000
Meena 02 2600.000
int main()
{
/*declare structure variable*/
struct employee emp;
10
CS3251 Programming in C – UNIT IV
11
CS3251 Programming in C – UNIT IV
1. malloc() function
malloc() allocates N bytes in memory and return pointer to allocated memory. The
returned pointer contains link/handle to the allocated memory.
void * malloc(number_of_bytes);
• It returns void pointer (generic pointer). Which means we can easily typecast it
to any other pointer types.
• It accepts an integer number_of_bytes, i.e. total bytes to allocate in memory.
Note: malloc() returns NULL pointer on failure.
Example
int N = 10; // Number of bytes to allocate
int *ptr; // Pointer variable to store address
ptr = (int *) malloc(N * sizeof(int)); // Allocate 10 * 4 bytes in memory
Here,
• ptr is a pointer to integer to store address of the allocated memory.
• (int *) is typecast required. As, I mentioned above that malloc() return void *.
Hence, to work with void pointer we must typecast it to suitable type.
• N * sizeof(int) - Since size of int is not fixed on all compilers. Hence, to get size
of integer on current compiler I have used sizeof() operator.
2. calloc() function
12
CS3251 Programming in C – UNIT IV
3. realloc() function
When working with huge data and if the allocated memory is not sufficient to store data.
In that case, we need to alter/update the size of an existing allocated memory blocks
(which has been created by either malloc() or calloc()).
We use realloc() function to alter/update the size of exiting allocated memory blocks.
The function may resize or move the allocated memory blocks to a new location.
Syntax
void* realloc(ptr, updated_memory_size);
• Similar to all other functions for Dynamic Memory Allocation in C, it returns
void pointer. Which points to the address of existing or newly allocated memory.
• ptr is a pointer to memory block of previously allocated memory.
• updated_memory_size is new (existing + new) size of the memory block.
Example
13
CS3251 Programming in C – UNIT IV
int N = 10;
int *ptr;
ptr = (int *) malloc(N * sizeof(int));
4. free() function
C programming has a built-in library function free() to clear or release the unused
memory.
The free() function clears the pointer (assigns NULL to the pointer) to clear the
dynamically allocated memory. If pointer contains NULL, then free() does nothing
(because pointer will not be pointing at any memory addresses). If it contains any
address of dynamically allocated memory, free() will clear pointer by assigning NULL.
Syntax
free(ptr);
The function accepts a void pointer ptr. It points to previously allocated memory using
any of Dynamic Memory Allocation functions in C.
Example:
int N=10;
int *ptr;
// Allocate memory using malloc
ptr=(int *) malloc (N* size of (int));
//Free allocated memory
free(ptr);
14
CS3251 Programming in C – UNIT IV
• Linked list is a data structure which in turn can be used to implement other data
structures. Thus, it acts as building block to implement data structures like stacks,
queues and their variations.
• A linked list can be perceived as a train or a sequence of nodes in which each
node contain one or more data fields and a pointer to the next node.
START
1 2 3 4 5 6 7 X
In the above linked list, every node contains two parts- one integer and the other a
pointer to the next node. The left part of the node which contains data may include a
simple data type, an array or a structure. The right part of the node contains a pointer to
the next node (or address of the next node in sequence). The last node will have no next
node connected to it, so it will store a special value called NULL.
A singly linked list is the simplest type of linked list in which every node contains some
data and a pointer to the next node of the same data type. By saying that the node
contains a pointer to the next node we mean that the node stores the address of the next
node in sequence.
In this algorithm, we first initialize PTR with the address of start. So now PTR points
to the first node of the linked list.
Then in step 2 while loop is executed which is repeated till PTR processes the last node,
that is, until it encounters NULL.
In step 3, we apply the process to the current node.
In step 4, we move to the next node by making PTR point to the node whose address is
stored in the NEXT field.
The algorithm print the information stored in each node of the linked list is shown
below:
We will traverse each and every node of the list and while traversing every individual
node, we will increment the counter by 1. Once we reach NULL, that is when all the
nodes of the linked list have been traversed, the final value of the counter will be
displayed. Figure below shows the algorithm to print the number of nodes in a linked
list.
Consider the linked list shown in figure we have val=4, then the flow of the algorithm
can be explained as shown in figure
1 7 3 4 2 6 5 X
1 7 3 4 2 6 5 X
1 7 3 4 2 6 5 X
4.8.3 Insertion in a Singly Linked List
1 7 3 4 2 6 5 X
17
CS3251 Programming in C – UNIT IV
Insert a new node at the head of the list is straightforward. The main idea is that we
create a new node, set its next link to refer to the current head, and then set head to point
to the new node.
Algorithm addFirst(String newData):
create a new node v containing newData
v.setNext(head)
head = v
size = size + 1
18
CS3251 Programming in C – UNIT IV
Algorithm removeFirst()
if (head = = null) then
Indicate an error: the list is empty
tmp = head
head = head.getNext()
tmp.setNext(null)
size = size - 1
Example:
include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
};
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n"); return NULL;
}
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
19
CS3251 Programming in C – UNIT IV
}
struct test_struct* add_to_list(int val, bool add_to_end)
{
if(NULL == head)
{
return (create_list(val));
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else printf("\n Adding node to beginning of list with value [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{ printf("\n Node creation failed \n"); return NULL;
}
ptr->val = val;
ptr->next = NULL;
if(add_to_end)
{ curr->next = ptr; curr = ptr;
}
else { ptr->next = head; head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
20
CS3251 Programming in C – UNIT IV
if(ptr->val == val)
{ found = true; break;
}
else
{
tmp = ptr; ptr = ptr->next;
}
}
if(true == found)
{
if(prev) *prev = tmp;
return ptr;
}
else
{
return NULL; } }
int delete_from_list(int val)
{
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL) { return -1; }
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{ curr = prev;
}
else if(del == head)
21
CS3251 Programming in C – UNIT IV
{
head = del->next;
}}
free(del);
del = NULL; return 0;
}
void print_list(void) {
struct test_struct *ptr = head;
printf("\n -------Printing list Start------- \n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End------- \n"); return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true); print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{ ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
22
CS3251 Programming in C – UNIT IV
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val); }
print_list(); ret = delete_from_list(i);
if(ret != 0) { printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i); } print_list(); } return 0;
}
4.9 Typedef
The typedef keyword enables the programmer to create a new data type name by using
an existing data type.
By using typedef, no new data is created, rather an alternate name is given to a known
data type.
Syntax: typedef existing_data_type new_data_type;
23
CS3251 Programming in C – UNIT IV
2. A data structure that can store related information of different data types
together is
A. array
B. string
C. Structure
D. all of these
Answer: Structure
24
CS3251 Programming in C – UNIT IV
25
CS3251 Programming in C – UNIT IV
26
CS3251 Programming in C – UNIT IV
27