Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
19 views23 pages

Unit - Iv Structures

This document discusses structures in C programming, including their definition, access methods, and usage in various contexts such as nested structures and pointers. It provides examples of defining structures for books and employees, accessing their members, and using arrays of structures to manage multiple records. Additionally, it covers dynamic memory allocation for structures and methods to copy structures in C.

Uploaded by

shalinipazhani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views23 pages

Unit - Iv Structures

This document discusses structures in C programming, including their definition, access methods, and usage in various contexts such as nested structures and pointers. It provides examples of defining structures for books and employees, accessing their members, and using arrays of structures to manage multiple records. Additionally, it covers dynamic memory allocation for structures and methods to copy structures in C.

Uploaded by

shalinipazhani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

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.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;
};

Accessing Structure Members


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];
char author[50];
79
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* 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;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title); printf( "Book 1 author : %s\n", Book1.author); printf(
"Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title); printf( "Book 2 author : %s\n", Book2.author); printf(
"Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

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("\n\tEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\n\tEnter Employee Salary : ");


scanf("%f",&E.Salary);
printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.HouseNo);

printf("\n\tEnter Employee City : ");


scanf("%s",&E.Add.City);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.PinCode);

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 :

Enter Employee Id : 101


Enter Employee Name : Suresh Enter
Employee Salary : 45000 Enter Employee
House No : 4598/D Enter Employee City :
Delhi
Enter Employee Pin Code : 110056

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:

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

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("Enter integer: "); scanf("%d",&(*personPtr).age);

printf("Enter number: "); scanf("%f",&(*personPtr).weight);

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.

Using -> operator to access structure pointer member


Structure pointer member can also be accessed using -> operator.

(*personPtr).age is same as personPtr->age

(*personPtr).weight is same as personPtr->weight

2.Accessing structure member through pointer using dynamic memory allocation


To access structure member using pointers, memory can be allocated dynamically using
malloc() function defined under "stdlib.h" header file.

Syntax to use malloc()

ptr = (cast-type*) malloc(byte-size)

Example to use structure's member through pointer using malloc() function


#include <stdio.h> #include
<stdlib.h> struct person {
int age;
float weight; char
name[30];
};

int main()
{
struct person *ptr; int i, num;
83
printf("Enter number of persons: ");
scanf("%d", &num);

ptr = (struct person*) malloc(num * sizeof(struct person));


// Above statement allocates the memory for n structures with pointer personPtr pointing to base
address */

for(i = 0; i < num; ++i)


{
printf("Enter name, age and weight of the person respectively:\n"); scanf("%s%d%f", &(ptr+i)-
>name, &(ptr+i)->age, &(ptr+i)->weight);
}

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

Enter number of persons: 2


Enter name, age and weight of the person respectively: Adam
2
3.2
Enter name, age and weight of the person respectively:

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];

// 1st student's record record[0].id=1;


strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;

// 3rd student's record record[2].id=3;


strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;

for(i=0; i<3; i++)


{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}

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};

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", record1.id); printf("
Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);

printf("Records of STUDENT2: \n");


printf(" Id is: %d \n", record2.id); printf("
Name is: %s \n", record2.name);
printf(" Percentage is: %f \n\n", record2.percentage);
return 0;
}
OUTPUT:
Records of STUDENT 1:
Id is: 1
Name is: Raju
Percentage is: 90.500000

Records of STUDENT 2:
Id is: 2
Name is: Mani
Percentage is: 93.500000

4.5Example Program using structures and pointers


Example Program For C Structure Using Pointer:
In this program, “record1” is normal structure variable and “ptr” is pointer structure variable.
As you know, Dot(.) operator is used to access the data using normal structure variable and arrow(->)
is used to access data using pointer variable.

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

Records of STUDENT1 – Direct copy from record1


Id :1
Name :Raju
Percentage :90.500000

Records of STUDENT1 – copied from record1 using memcpy


Id :1
Name :Raju
Percentage :90.500000

Records of STUDENT1 – Copied individual members from record1


Id :1
Name :Raju
Percentage : 90.500000

4.6 Self referential structures


Consider the structure declaration below,

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;

/* accessing members of 'previous' */ previous.new =


&current;
/* previous.new is a 'pointer-to-struct NODE' */ previous.value
= 100;
}
4.7 Dynamic Memory Allocation
The C programming language manages memory statically, automatically, or
dynamically. Static variables are allocated in main memory, usually along with the
executable code of the program, and persist for the lifetime of the program; automatic
variables are allocated on the stack and come and go as functions are called and return. For
static and automatic variables, the size of the allocation must be compile-time constant
(except for the case of variable-length automatic arrays). If the required size is not known
until run-time (for example, if data of arbitrary size is being read from the user or from a disk
file), then using fixed-size data objects is inadequate.
The lifetime of allocated memory can also cause concern. Neither static- nor
automatic memory is adequate for all situations. Automatic-allocated data cannot persist
across multiple function calls, while static data persists for the life of the program whether it
is needed or not. In many situations the programmer requires greater flexibility in managing
the lifetime of allocated memory.

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.

Function Use of Function

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

free() deallocate the previously allocated space

realloc() Change the size of previously allocated space

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:

ptr = (int*) malloc(100 * sizeof(int));

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()

ptr = (cast-type*)calloc(n, element-size);

90
This statement will allocate contiguous space in memory for an array of n elements.
Example:

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements


each of size of float, i.e, 4 bytes.
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its
own. You must explicitly use free() to release the space.

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);

ptr = (int*) malloc(num * sizeof(int));


if(ptr == NULL)
{
printf("Error! Unable to allocate memory.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
}
for(i = 0; i < num; ++i)
{
sum += *(ptr + i);
}
printf("Sum of Elements in the given array is : %d", sum);
free(ptr);
return 0; }
Output:
Enter number of elements in the Array: 5
Enter elements of array:6
20
15
4
8
91
Sum of Elements in the given array is : 53

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;

printf("Enter number of elements in the Array: ");


scanf("%d", &num);

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL)
{
printf("Error! Unable to allocate memory.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
}
for(i = 0; i < num; ++i)
{
sum += *(ptr + i);
}

printf("Sum of Elements in the given array is : %d", sum);


free(ptr);
return 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()

ptr = realloc(ptr, newsize);

Here, ptr is reallocated with size of newsize.


Example: for realloc()

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, num2,i, *ptr, sum = 0;

printf("Enter number of elements in the Array: ");


scanf("%d", &num);

ptr = (int*) calloc(num, sizeof(int));


if(ptr == NULL)
{
printf("Error! Unable to allocate memory.");
exit(0);
}

printf("Enter elements of array: ");


for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
}
for(i = 0; i < num; ++i)
{
sum += *(ptr + i);
}
printf("Sum of Elements in the given array is : %d", sum);
printf("\nWant to add more element in array!"); printf("\nEnter
number of New elements in the Array: "); scanf("%d", &num2);
ptr = realloc(ptr,num2);
if(ptr == NULL)
{
printf("Error! Unable to allocate memory.");
exit(0);
}

printf("\nEnter New elements of array: "); for(i


= num; i < num+num2; ++i)
{
scanf("%d", ptr + i);
}
sum=0;
93
for(i = 0; i < num+num2; ++i)
{
sum += *(ptr + i);
}
printf("\nSum of all Elements in the given array is : %d", sum); free(ptr);
return 0;
}
Output:
Enter number of elements in the Array: 3
Enter elements of array:5
20
8
Sum of Elements in the given array is : 33
Want to add more elements in the array!
Enter number of elements in the Array: 2
Enter new elements of array:4
6
Sum of all Elements in the given array is : 43
Here realloc() function is used to reallocate the size of the array, that was created
using calloc() function to add extra elements in the array.

4.8 singly linked list


A linked list contains a series of structures, which are not necessarily adjacent in
memory. Each node contains a data part and a link/pointer to the next successive node. The
last node‟s link is NULL. The first node is identified by a separate pointer variable first. A
list which is unidirectional where each structure points to its succeeding structure is called a
singly linked list. The nodes of the list are accessed by traversing through using a temporary
variable.

(a) Singly linked list representation

(b) Singly linked list showing actual address values


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;
};

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.

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.

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

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 ;

typedef in user defined data type


typedef can be used to give a name to user defined data type as well. Lets see its use with
structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name ;

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

Student name is: raju


Student mark is: 98-

typedef and Pointers


typedef can be used to give an alias name to pointers also. Here we have a case in which use
of typedef is beneficial during pointer declaration.
In Pointers * binds to the right and not the left.
int* x, y ;
By this declaration statement, we are actually declaring x as a pointer of type int, whereas y
will be declared as a plain integer.
typedef int* IntPtr ;

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

You might also like