0% found this document useful (0 votes)
24 views25 pages

Unit Iv

The document provides an overview of structures in C programming, covering topics such as defining structures, accessing members, nested structures, pointers, dynamic memory allocation, and arrays of structures. It includes example programs demonstrating the use of structures for managing data like books and student records. The document emphasizes the importance of structures for organizing complex data types in C.

Uploaded by

thirunavukkarasu
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)
24 views25 pages

Unit Iv

The document provides an overview of structures in C programming, covering topics such as defining structures, accessing members, nested structures, pointers, dynamic memory allocation, and arrays of structures. It includes example programs demonstrating the use of structures for managing data like books and student records. The document emphasizes the importance of structures for organizing complex data types in C.

Uploaded by

thirunavukkarasu
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/ 25

CS8251 Dept of CSE Programming in C

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

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

Employee structure and create an object of Address structure inside Employee


structure.
Syntax for structure within structure or nested structure

struct structure1
{
----------
----------
};

struct structure2
{
----------
----------
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);

TPGIT/CSE 3
CS8251 Dept of CSE Programming in C

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

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.3 Pointer and Structures

Structures can be created and accessed using pointers. A pointer variable of a


structure can be created as below:

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("Enter integer: ");


scanf("%d",&(*personPtr).age);

printf("Enter number: ");


scanf("%f",&(*personPtr).weight);

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.

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

TPGIT/CSE 5
CS8251 Dept of CSE Programming in C

(*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;

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:

TPGIT/CSE 6
CS8251 Dept of CSE Programming in C

Eve
6
2.3
Displaying Information:
Adam 2 3.20
Eve 6 2.30

4.4 Array 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.
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;

TPGIT/CSE 7
CS8251 Dept of CSE Programming in C

// 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.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
Example Program For Declaring Many Structure Variable In C:
In this program, two structure variables “record1″ and “record2″ are declared for
same structure and different values are assigned for both structure variables.
Separate memory is allocated for both structure variables to store the data.
Program:
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[30];
float percentage;
};

int main()
{
int i;

TPGIT/CSE 8
CS8251 Dept of CSE Programming in C

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 STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000

4.5 Example 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>

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

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 STUDENT1:
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
3. we can copy by individual structure members.

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

32. // 2nd method to copy using memcpy function


33. ptr1 = &record1;
34. memcpy(record3, ptr1, sizeof(record1));
35.
36. printf("\nRecords of STUDENT1 - copied from record1 " \
37. "using memcpy \n");
38. printf(" Id : %d \n Name : %s\n Percentage : %f\n",
39. record3->id, record3->name, record3->percentage);
40.
41. // 3rd method to copy by individual members
42. printf("\nRecords of STUDENT1 - Copied individual " \
43. "members from record1 \n");
44. record4.id=record1.id;
45. strcpy(record4.name, record1.name);
46. record4.percentage = record1.percentage;
47.
48. printf(" Id : %d \n Name : %s\n Percentage : %f\n",
49. record4.id, record4.name, record4.percentage);
50.
51. return 0;
52. }
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;

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;

/* 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

TPGIT/CSE 12
CS8251 Dept of CSE Programming in C

program whether it is needed or not. In many situations the programmer requires


greater flexibility in managing the lifetime of allocated memory.
These limitations 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(informally called the "heap"). In C, the library function malloc is
used to allocate a block of memory on the heap. The program accesses this block of
memory via a pointer that malloc returns. When the memory is no longer needed,
the pointer is passed to free which deallocates the memory so that it can be used for
other purposes.
Some platforms provide library calls which allow run-time dynamic allocation from
the C stack rather than the heap (e.g. 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

Allocates requested size of bytes and returns a pointer first byte of


malloc()
allocated space

Allocates space for an array elements, initializes to zero and then returns
calloc()
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".

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

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

This statement will allocate contiguous space in memory for an array of n elements.
For 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);
}

TPGIT/CSE 14
CS8251 Dept of CSE Programming in C

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


free(ptr);
return 0;
}

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;

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:

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

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)

TPGIT/CSE 16
CS8251 Dept of CSE Programming in C

{
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;
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:

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

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

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

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>

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

TPGIT/CSE 24
CS8251 Dept of CSE Programming in C

getch();
}
Output:

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.

TPGIT/CSE 25

You might also like