0% found this document useful (0 votes)
4 views

unit 4

The document provides an overview of structures in C programming, including their declaration, initialization, and usage. It covers nested structures, typedef declarations, and arrays of structures, along with example code snippets. Key concepts such as accessing members, copying structures, and dynamic memory allocation are also discussed.

Uploaded by

vini t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

unit 4

The document provides an overview of structures in C programming, including their declaration, initialization, and usage. It covers nested structures, typedef declarations, and arrays of structures, along with example code snippets. Key concepts such as accessing members, copying structures, and dynamic memory allocation are also discussed.

Uploaded by

vini t
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

CS8251-PROGRAMMING IN C

IV UNIT- STRUCTURES ➢ For example, if we have to define a structure for a student, then its
related information probably would be: roll_number, name, course,
Structure - Nested structures – Pointer and Structures – Array of and fees.
structures – Example Program using structures and pointers –
➢ This structure can be declared as:
Self- referential structures – Dynamic memory allocation - Singly
linked list - typedef Eg:
struct student
4.1 INTRODUCTION {
int r_no;
➢ A structure is similar to records. char name[20];
➢ It stores related information about an entity. char course[20];
➢ A structure is a user-defined data type that can store related
float fees;
information (even of different data types) together.
};
➢ The major difference between a structure and an array is that,
➢ Now, the structure has become a user-defined data type.
an array contains related information of the same data type.
➢ Each variable name declared within a structure is called a member
➢ A structure is, therefore, a collection of variables under a single
of the structure.
name.
➢ The structure declaration however, does not allocate any memory
➢ The variables within a structure are of different data types and
or consume storage space.
each has a name that is used to select it from the structure.
➢ Like any data type, memory is allocated for the structure when we
declare a variable of the structure.
4.1.1 Structure Declaration
➢ For example, we can define a variable student by writing
➢ A structure is declared using the keyword struct followed by a
structure name. struct student stud1;
➢ All the variables of the structure are declared within the structure. Here, struct student is a data type and stud1 is a variable.
➢ A structure type is generally declared by using the following syntax: Eg:
struct struct-name struct student
{ {
data_type var-name; int roll_no;
data_type var-name; char name[20];
……………….. char course[20];
}; float fees;

1
CS8251-PROGRAMMING IN C

}stud1, stud2; ➢ Initializing a structure means assigning some constants to the


➢ In this declaration we declare two variables studl and stud2of the members of the structure.
structure student. ➢ The initializers are enclosed in braces and are separated by
commas.
➢ So if you want to declare more than one variable of the structure,
➢ However, care must be taken to see that the initializers match their
then separate the variables using a comma. corresponding types in the structure definition.
➢ When we declare variables of the structure, separate memory is
allocated for each variable. Syntax:
The general syntax to initialize a structure variable is given as follows:
struct struct_name
{
data_type member_namel;
data_type member_name2;
data_type member_name3;
}struct_var = {constantl, constant2,constant 3, ...};
OR
struct struct_name
{
data_type member_narnel;
data_type member_narne2;
data_type member_narne3;
………………
};
➢ Structure member names and names of the structure follow the
struct struct_name struct_var = {constant 1, constant2, constant
same rules as laid down for the names of ordinary variables.
3};
➢ However, care should be taken to ensure that the name of structure
Eg:
and the name of a structure member should not be the same.
struct student
➢ Moreover, structure name and its variable name should also be
{
different.
int r no;
char name [20];
4.1.2 Initialization of Structures
char course[20];
float fees;
➢ A structure can be initialized in the same way as other data types are
}studl={01,"Rahul","BCA",45000};
initialized.

2
CS8251-PROGRAMMING IN C

OR scanf(“%d”,&stud1.r_no);
by writing scanf(“%s”,stud1.name);
struct student studl = {01,"Rahul","BCA",45000};
➢ To print the values of structure variable studl, we may write
printf("%s", studl.course);
printf("%f", studl.fees);

4.1.4 Copying and Comparing Structures

➢ We can assign a structure to another structure of the same type.


➢ For example, if we have two structure variables studl and stud2 of
type struct student given as
struct student studl = {01, "Rahul”, "BCA" , 45000};
struct student stud2;
➢ Then to assign one structure variable to another we will write,
stud2 = studl;
This statement initializes the members of stud2 with the values of
4.1.3 Accessing the Members of a Structure members of studl.

➢ A structure member variable is generally accessed using a ‘.’


(dot)operator.
➢ The syntax of accessing a structure or a member of a structure can be
given as:
struct var.member name
➢The dot operator is used to select a particular member of the
structure.
➢ For example, to assign value to the individual data members of the
structure variable studl, we may write
Eg:// Student details
studl.r no =01;
#include<stdio.h>
studl.name="Rahul" ;
#include<conio.h>
studl.course = "BCA";
int main()
studl.fees = 45000;
{
➢ To input values for data members of the structure variable studl,
struct student
we may write
3
CS8251-PROGRAMMING IN C

{ DOB = 25-09-1991
int roll_no;
char name[80]; Eg:// Largest of 3 nos
float fees; #include <stdio.h>
char DOB[80]; #include <conio.h>
}; int main()
struct student stud1; {
clrscr (); struct numbers
printf ("\n Enter the roll number: "); {
scanf("%d",&stud1.roll_no); int a, b, c;
printf ("\n Enter the name: "); int largest;
scanf("%s",stud1.name); };
printf ("\n Enter the fees: "); struct numbers num;
scanf ("%f",&stud1.fees); clrscr ();
printf ("\n Enter the DOB:"); printf ("\n Enter the three numbers: ");
scanf("%s", stud1.DOB); scanf("%d %d %d", &num.a, &num.b, &num.c);
printf("\n ********STUDENT'S DETAILS*******"); if(num.a > num.b && num.a > num.c)
printf("\n ROLL No. = %d",stud1.roll_no); num.largest = num.a;
printf("\n NAME = %s",stud1.name); if(num.b > num.a && num.b > num.c)
printf("\n FEES = %f",stud1.fees); num.largest = num.b;
printf ("\n DOB = %s",stud1.DOB); if(num.c > num.a && num.c > num.b)
getch(); num.largest = num.c;
return 0; printf ("\n The largest number is: %d", num.largest);
} getch( );
Output return0;
Enter the roll number: 01 }
Enter the name: Rahul
Enter the fees: 45000 Output
Enter the DOB: 25-09-1991 Enter the three numbers: 7 9 1
********STUDENT'S DETAILS ******* The largest number is: 9
ROLL No= 01
NAME=Rahul
FEES=45000.00

4
CS8251-PROGRAMMING IN C

4.2 Typedef declarations int imag;


}COMPLEX;
➢ The typedef (derived from type definition) keyword enables the COMPLEX c1, c2 , sum_c, sub_c;
programmer to create a new data type name from an existing data int option;
type. clrscr();
➢ By using typedef, no new data is created, rather an alternate name is do
given to a known data type. printf("\n *** MAINMENU***");
➢ The general syntax of using the typedef keyword is given as: printf("\n 1. Read the complex nos.");
typedef existing data_type new data_type printf ("\n 2. Display the complex nos.");
printf ("\n 3. Add the complex nos. ");
For example, if we write printf ("\n 4. Subtract the complex nos.") ;
typedef int INTEGER; printf("\n 5. EXIT");
INTEGER num=5; printf (" \n Enter your option: ");
scanf("%d", &option);
Eg: switch (option)
typedef struct student case 1:
{ printf (" \n Enter the real and imaginary parts of the first complex
int r_no; number: ");
char name [20]; scanf ("%d%d", &c1. real, &c1.imag);
char course [20]; printf (" \n Enter the real and imaginary parts of the second
float fees; complex number: ");
}; scanf ("%d%d", &c2. real, &c2.imag);
To declare a variable of structure student you will just write break;
student studl; case 2:
printf ("\n The first complex number is:%d+ %di" , c1. real, c1. imag);
Eg:// complex numbers printf ("\n The second complex number is :%d+ %di" , c2. real, c2.
#include <stdio.h> imag);
#include <conio.h> break;
int main ()
{ case 3:
typedef struct complex sum_c. real = c1 . real + c2 . real;
{ sum_c. imag = c1. imag + c2. imag;
int real;

5
CS8251-PROGRAMMING IN C

printf("\n The sum of two complex numbers is: %d+%di", Eg://Enter two points and then calculate the distance between
sum_c.real,sum_c.imag); them.
break; #include <stdio.h>
case 4: #include <conio.h>
sub_c.real = c1.real - c2.real; #include<math.h>
sub_c.imag = c1.imag - c2.imag; int main()
printf ("\n The difference between two complex numbers is: %d+ %di", typedef struct point
sub_c.real,sub_c.imag); {
break; int x, y;
} }POINT;
}while(option != 5); POINT p1, p2;
getch(); float distance;
return 0; clrscr ();
} printf("\n Enter the coordinates of thefirst point: ");
Output scanf ("%d %d", &p1.x , &p1.y);
1. Read the complex numbers printf("\n Enter the coordinates of the second point: " );
2. Display the complex numbers scanf ("%d %d", &p2.x, &p2.y);
3. Add the complex numbers distance = sqrt (pow( (p1.x - p2 .x) , 2) +pow( (p1.y - p2.y), 2) );
4. Subtract the complex numbers printf (" \n The coordinates of the first point are: %dx %dy”, p1.x,
5. EXIT pl. y);
Enter your option: 1 printf ("\n The coordinates of the second point are: %dx %dy",
Enter the real and imaginary parts of the p2.x, p2.y);
first complex number: 2 3 printf("\n Distance between p1 and p2%f",distance);
Enter the real and imaginary parts of the getch();
second complex number: 4 5 return 0;
******** MAINMENU********* }
1. Read the complex numbers Output
2. Display the complex numbers Enter the coordinates of the first point: 2 3
3. Add the complex numbers Enter the coordinates of the second point: 9 9
4. Subtract the complex numbers The coordinates of the first point are: 2x 3y
5. EXIT The coordinates of the second point are: 9x 9y
Enter your option: 3 Distance between p1 and p2 = 9.219544
The sum of two complex numbers is: 6 + 8i

6
CS8251-PROGRAMMING IN C

4.3 NESTED STRUCTURES scanf ("%d",&studl.roll_no);


printf (" \n Enter the name: ");
➢ A structure can be placed within another structure, i.e., scanf("%s",studl.name);
➢ A structure may contain another structure as its member. printf(" \n Enter the fees: ");
➢ A structure that contains another structure as its member is called a scanf("%f", &studl.fees);
nested structure. printf("\n Enter the DOB:”);
➢ The easier and clearer way is to declare the structures separately scanf("%d%d%d",&studl.date.day,&studl.date.month,&studl.date.year)
and then group them in a high level structure. ;
➢ When you do this, take care to check that nesting must be done printf("\n *** STUDENT'SDETAILS***”);
from inside out (from lowest level to the most inclusive level), i.e., printf ("\n ROLLNo. = %d",studl.roll_no);
to say, declare the inner most structure, then the next level printf ("\n NAME= %s",studl.name);
structure, working towards the outer (most inclusive) structure. printf ("\n FEES = %f",studl. fees);
Eg: printf("\nDOB=%d-%d-
#include <stdio.h> %d”,stud1.date.day,stud1.date.month,stud1.date.year);
#include <conio.h> getch();
int main() return 0;
{ }
struct DOB Output
{ Enter the roll number: 01
int day; Enter the name: Rahul
int month; Enter the fees: 45000
int year; Enter the DOB: 25 09 1991
}; ********STUDENT'S DETAILS *******
struct student ROLL No. = 01
{ NAME = Rahul
int roll_no; FEES = 45000.00
char name[100] ; DOB = 25-09-1991
float fees;
struct DOBdate; Eg:
}; typedef struct
struct student studl; {
clrscr (); char first_name [20] ;
printf("\n Enter the roll number:”); char mid_name [20] ;

7
CS8251-PROGRAMMING IN C

char last_name [20] ; 4.4 ARRAYS OF STRUCTURES


}NAME;
➢ In a class, we do not have just one student.
typedef struct ➢ But there may be at least 30 students. So the same definition of the
{ structure can be used for all the 30 students.
int dd; ➢ This would be possible when we create an array of the structure.
int mm; ➢ An array of a structure is declared in the same way as we declare an
int yy; array of a built-in data type.
}DATE; ➢ The general syntax for declaring an array of a structure given as
struct struct_name
typedef struct student {
{ data_type member_name1;
int r_no; data_type member_name2;
NAME name; data_type member_name3;
char course [20] ; ………………………..
DATE DOB; };
float fees; struct struct_name struct_var[index];
}; Eg:
int main() #include <stdio.h>
{ #include <conio.h>
student studl; int main()
clrscr(); {
studl.name.first_name = "Janak"; struct student
studl.name.mid_name = "Raj"; {
studl.name.last name = "Thareja"; int roll_no;
studl.course = "BCA"; char name[80];
studl.DOB.dd = 15; int fees;
studl.DOB.mm = 09; char DOB[80];
studl.DOB.yy = 1990; };
studl. fees = 45000; struct student stud[50];
getch(); int n, i;
return 0; clrscr();
} printf("\n Enter the number of students:”);

8
CS8251-PROGRAMMING IN C

scanf ("%d", &n); Enter the DOB: 27 8 91


for(i = 0;i < n;i++) ********DETAILS OF STUDENT 1*******
{ ROLLNo. = 1
printf ("\n Enter the roll number:"); NAME= kirti
scanf("%d", &stud [i].roll_no); FEES = 5678
printf("\n Enter the name:"); DOB = 9 9 91
gets(stud[i].name); ********DETAILS OF STUDENT2*******
printf("\n Enter the fees:"); ROLLNo. = 2
scanf("%d", &stud[i].fees); NAME= kangana
printf ("\n Enter the DOB: "); FEES = 5678
gets (stud[i].DOB); DOB = 27 8 91
}
for (i = 0; i <n; i++) 4.5 STRUCTURES AND POINTERS
{
printf("\n ********DETAILS OF STUDENT%d ******, i+l); Passing Structures Through Pointers
printf("\n ROLLNo = %d", stud[i].roll_no);
printf("\n NAME= %s", stud[i].name); ➢ Passing large structures to functions using the call by value method
printf ("\n FEES = %d", stud [i].fees); is very inefficient.
printf("\n DOB = %s", stud[i].DOB); ➢ Therefore, it is preferred to structures through pointers.
} ➢ The syntax to declare a pointer to a structure can be given as
getch(); struct struct name
return 0; {
} data_type member_namel;
Output data_type member_name2;
Enter the number of students: 2 data_type member_name3;
Enter the roll number: 1 ……………………………
Enter the name: kirti }*ptr;
Enter the fees: 5678 OR
Enter the DOB: 9 9 91 struct struct_name *ptr;
➢ we can declare a pointer variable by writing
Enter the roll number: 2 struct student *ptr_stud, stud;
Enter the name: kangana ➢ The next thing to do is to assign the address of stud to the pointer
Enter the fees: 5678 using the address operator (&).

9
CS8251-PROGRAMMING IN C

ptr_stud=&stud; gets(ptr _stud2 -> course);


➢ To access the members of the structure, one way is to write printf("\n Enter the Fees = ");
ptr_stud-> roll_no = 01; scanf("%d", &ptr_stud2 -> fees);

Eg:// Details of a student printf(" \n DETAILSOF FIRST STUDENT");


#include<stdio.h> printf ("\n ROLLNUMBER = %d",ptr_stud1->r_no);
#include<conio.h> printf("\n NAME= %s", ptr_studl->name);
struct student printf("\n COURSE= %s", ptr_studl->course);
{ printf("\n FEES = %d", ptr_studl-> fees);
int r_no;
char name[20]; printf("\n\n\n\n DETAILSOF SECOND STUDENT");
char course[20]; printf ("\n ROLLNUMBER = %d",ptr_stud2->r_no);
int fees; printf ("\n NAME= %s", ptr_stud2 ->name);
}; printf ("\n COURSE= %s", ptr_stud2->course);
int main() printf ("\n FEES = %d", ptr_stud2 -> fees);
{ return 0;
struct student studl, stud2, *ptr_studl, *ptr_stud2; }
clrscr (); Output
Enter the details of the second student:
ptr_studl = &studl; Enter the Roll Number = 02
ptr_stud2 = &stud2; Enter the Name = Aditya
Enter the Course =MCA
ptr_studl->r_no = 01; Enter the Fees = 60000
strcpy (ptr_studl-> name, "Rahul "); DETAILSOF FIRST STUDENT
strcpy (ptr _studl -> course, "BCA"); ROLLNUMBER= 01
ptr_studl->fees = 45000; NAME= Rahul
COURSE = BCA
printf("\n Enter the details of the second student:"); FEES = 45000.00
printf (" \n Enter the Roll Number =");
scanf ("%d", &ptr_stud2->r_no); DETAILS OF SECOND STUDENT
printf (" \n Enter the Name = "); ROLL NUMBER = 02
gets(ptr_stud2 ->name); NAME Aditya
printf("\n Enter the Course = "); COURSE = MCA

10
CS8251-PROGRAMMING IN C

FEES = 60000.00
Eg: // Get the inch details from the user and calculate the distance
Eg:// student details using assignment statement using the structures

#include <stdio.h> #include<stdio.h>


#include <conio.h> #include<conio.h>
struct student struct Distance
{ {
int r_no; int feet;
char name [20]; float inch;
char course [20]; }d1,d2,sum;
float fees;
}; int main()
int main() {
{ printf( “ enter the information for first distance”);
struct student *ptr_studl; printf(“ enter the feet ”);
struct student studl = {01, "Rahul" , "BCA" , 45000}; scanf(“%d”,&d1.feet);
clrscr(); printf(“ enter the inch ”);
ptr_studl = &studl; scanf(“%f”,&d1.inch);

printf ("\n DETAILS OF STUDENT"); printf( “ enter the information for second distance”);
printf("\n ROLL NUMBER = %d", ptr_studl->r_no); printf(“ enter the feet ”);
printf ("\n NAME = %s ". ptr_studl ->name) ; scanf(“%d”,&d2.feet);
printf("\n COURSE = %s", ptr_studl->course); printf(“ enter the inch ”);
printf("\n FEES = %f", ptr_studl-> fees); scanf(“%f”,&d2.inch);
return 0; sum.feet=d1.feet+d2.feet;
} sum.inch=d1.inch+d2.inch;
Output // If inch >12, change it to feet
DETAILS OF STUDENT
ROLL NUMBER = 01 if(sum.inch>12.0)
NAME = Rahul {
COURSE = BCA sum.inch=sum.inch-12.0;
FEES = 45000.00 ++sum.feet;

11
CS8251-PROGRAMMING IN C

}
printf(“ sum of distances = %d - %lf ”,sum.feet,sum.inch); 4.7 DYNAMIC MEMORY ALLOCATION
return 0;
} ➢ The process of allocating memory to the variables during
Output: execution of the program or at run time is known as dynamic
Enter the information for first distance memory allocation.
Enter feet: 23 ➢ Till now whenever we needed an array we had declared a static
Enter inch : 8.6 array of fixed size, say int arr[100] ;
➢ When this statement is executed, consecutive space for100 integers
Enter the information for second distance is allocated.
Enter feet: 34 ➢ It is not uncommon that we may be using only 10% or 20% of the
Enter inch : 2.4 allocated space there by wasting rest of the space.
Sum=57-11.0 ➢ To overcome this problem and to utilize the memory efficiently c
language provides a mechanism of dynamically allocating memory
4.6 SELF-REFERENTIAL STRUCTURES so that only the amount of memory that is actually required is
➢ A structure that includes at least one member which is a pointer to reserved.
the same structure type. ➢ We reserve space only at the run time for the variables that are
Syntax: actually required.
struct struct_name
{
member 1;
member 2;
………….
member n;
struct struct_name*name;
};
Eg:
struct student_node
{
int roll_no;
char name[20]; ➢ When we have to dynamically allocate memory for variables in
struct student_node *next; our programs then pointers are the only way to go.
};

12
CS8251-PROGRAMMING IN C

Allocating a Block of Memory ptr=(struct emp*)malloc(sizeof(struct emp));


Malloc if(ptr==NULL)
➢ Let us see how memory is allocated using the malloc() . {
➢ malloc is declared in <stdlib.h>, so we include this header file in printf(“ Out of memory “);
any program that calls malloc. }
➢ The malloc function reserves a block of memory of specified size else
and returns a pointer of type void. This means that we can assign it {
to any type of pointer. printf(“ Enter the employee details ”);
➢ The general syntax of the malloc() is scanf(“%d%s%d”,&ptr->roll_no,ptr->name,&ptr->salary);
ptr =(cast-type*)malloc(byte-size); printf(“%d%s%d”,ptr->roll_no,ptr->name,ptr->salary);
where ptr is a pointer of type cast-type. }
➢ The malloc()returns a pointer (of cast type) to an area of memory
with size byte-size. Calloc
➢ For example, arr=(int*)malloc(n*sizeof(int)) ;// for array ➢ The function calloc() is another function that reserves memory at
This statement is used to dynamically allocate memory equivalent the run time.
to n times the area of int bytes. ➢ It is normally used to request multiple blocks of storage each of the
➢ On successful execution of the statement the space is reserved and same size and then sets all bytes to zero.
the address of the first byte of memory allocated is assigned to the ➢ calloc() stands for contiguous memory allocation and is primarily
pointer arr of type int. used to allocate memory for arrays.
➢ a null pointer will be returned if there is not enough space in the ➢ The syntax of calloc() canbe given as
system to allocate. ptr=(cast-type*)calloc(n,elem-size);
➢ The above statement allocates contiguous space for n blocks each
Eg: size of elements size bytes.
#include<stdio.h> ➢ The only difference between malloc() and calloc() is that when we
#include<conio.h> use calloc(), all bytes are initialized to zero.
#include<stdlib.h> ➢ calloc() returns a pointer to the first byte of the allocated region.
struct emp ➢ When we allocate memory using malloc() or calloc(), a null
{ pointer will be returned if there is not enough space in the system
int roll_no; to allocate.
char name[20]; ➢ A null pointer, points definitely nowhere. It is a not a pointer
int salary; marker therefore, it is not a pointer you can use.
}; ➢ Thus, whenever you allocate memory using malloc() or calloc(),
struct emp *ptr; you must check the returned pointer before using it.

13
CS8251-PROGRAMMING IN C

Eg: Using calloc() read and display values of a integer arrays


Eg: //Using malloc() read and display values of a integer arrays
#include<stdio.h> ➢ The calloc() function accepts two parameters-num and size, where num
#include<conio.h> is the number of elements to be allocated and size is the size of
#include<stdlib.h> elements.
main() Eg:
{ #include<stdio.h>
int i, n·; #include<stdlib.h>
int *arr; main()
clrscr(); {
printf("\n Enter the number of elements "); int i,n.
scanf ("%d", &n); int *arr;
arr = (int*)malloc(n * sizeof(int)); printf ("\n Enter the number of elements: ");
if (arr == NULL) scanf(“%d”,&n);
{ arr = (int*)calloc(n,sizeof(int) ) ;
printf("\n Memory Allocation Failed"); if (arr==NULL)
exit (0) ; exit (1);
} printf("\n Enter the %d values to be stored in the array", n) ;
for(i=0;i<n;i++) for(i=0; i<n; i++)
{ scanf ("%d",&arr[i]);
printf("\n Enter the value %d of the array: ", i); printf(“ \nYou have entered: ");
scanf ("%d", &arr [i] ) ; for(i=0; i<n; i++)
} printf ("%d",arr[i]);
printf("\n The array contains \n"); free(arr) ;
for(i=0;i<n;i++) return 0;
printf("%d", arr[i]); }
return 0;
} realloc()(To Alter the Size of Allocated Memory)

➢ At times the memory allocated by using calloc() or malloc() might


be insufficient or in excess.

14
CS8251-PROGRAMMING IN C

➢ In both the situations we can always use realloc() to change the if(str==NULL)
memory size already allocated by calloc() and malloc().This process {
is called reallocation of memory. printf (" \n Memory could not be allocated") ;
➢ The general syntax for realloc() can be given as exit(l) ;
➢ ptr = realloc(ptr,newsize); }
➢ The function realloc() allocates new memory space of size specified strcpy(str,"Hi");
by newsize to the pointer variable ptr. printf("\n STR = %s", str);
➢ It returns a pointer to the first byte of the memory block. str=(char *)realloc(str,20);
➢ The allocated new block may be or may not be at the same region. if(str==NULL)
Thus, we see that realloc() takes two arguments. {
➢ The first is the pointer referencing the memory and the second is the printf("\n Memory could not be reallocated") ;
total number of bytes you want to reallocate. exit(1) ;
➢ If you pass zero as the second argument, itwill be equivalent to }
calling free (). printf("\n STR size modified.\n");
➢ Like malloc() and calloc(),realloc returns a void pointer if printf ("\n STR = %s\n", str);
successful, else a NULL pointer is returned. strcpy(str,"Hi there");
➢ If realloc() was able to make the old block of memory bigger, it printf("\n STR = %s", str);
returns the same pointer. free(str) ;
➢ Otherwise, if realloc() has to go elsewhere to get enough contiguous return 0;
memory then it returns a pointer to the new memory, after copying }
your old data there.
➢ However, if realloc() can't find enough memory to satisfy the new free() (Releasing the used space)
request at all, it returns a null pointer. So again you must check ➢ When a variable allocated space during the compile time, then the
before using, that the pointer returned by the realloc() is not a null memory used by that variable is automatically released by the
pointer. system in accordance with its storage class.
➢ But when we dynamically allocate memory then it is our
Eg: responsibility to release the space when it is not required.
#include< stdio. h>· ➢ Therefore, if we no longer need the data stored in a particular block
#include< stdlib.h> of memory and we do not intend to use that block for storing any
#define NULL 0 other information, then as a good programming practice we must
main() release that block of memory for future use, using the free function.
char *str; ➢ The general syntax of the free() is, free(ptr) ;where ptr is a pointer
str=(char *)malloc(10); that has been created by using malloc() or calloc().

15
CS8251-PROGRAMMING IN C

➢ When memory is de-allocated using the free(), it is returned back to


the free list within the heap. struct node
{
4.8 SINGLY LINKED LISTS int data;
struct node *next;
➢ 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 struct node *root=NULL;
data type. // insert a node in the beginning
➢ By saying that the node contains a pointer to the next node we mean void append()
that the node stores the address of the next node in sequence. {
Creating a Singly Linked List struct node*temp;
Eg: temp=(struct node*)malloc(sizeof(struct node));
struct node printf(“Enter the node data”);
{ scanf(“%d”,&temp->data);
int data; temp->next=NULL;
struct node *next; if(root==NULL)
}; {
struct node *root=NULL; root=temp;
}
void create() // insert a node to the last
{ else
struct node *temp; {
temp=(struct node*)malloc(sizeof(struct node)); struct node*p;
temp->next=NULL; p=root;
root=temp; while(p->next!=NULL)
} {
Inserting a New Node in a Linked List p=p->next;
Case 1 The new node is inserted at the beginning of a linked list }
Case 2 The new node is inserted at the end of a linked list p->next=temp;
Case 3 The new node is inserted after a given node }
Case 4 The new node is inserted before a given node }
void display()
Eg://insert a node at the beginning and at the end of the linked list {

16
CS8251-PROGRAMMING IN C

struct node*temp; p=p->next;


temp=root; i++;
if(temp==NULL) }
{ temp=(struct node*)malloc(sizeof(structnode));
printf(“ No nodes in the list “); printf(“Enter the node data”);
} scanf(“%d”,&temp->data);
else temp->next=NULL;
{ temp->next=p->next; [right side]
while(temp!=NULL) p->next=temp; [left]
{ }
printf(“%d”,temp->data); void display()
temp=temp->next; {
} struct node*temp;
} temp=root;
if(temp==NULL)
Eg:// Insert a node after a specified position {
void add_after() printf(“ No nodes in the list “);
{ }
struct node*temp; else
int loc,len,i=1; {
printf(“ Enter the location ”); while(temp!=NULL)
scanf(“%d”,&loc); {
len=length(); printf(“%d”,temp->data);
if(loc>len) temp=temp->next;
{ }
printf(“ Invalid location”); }
printf(“Currently list is having %d nodes”,len); Traversing a Singly Linked List
}
else ➢ Traversing a linked list means accessing the nodes of the list in
{ order to perform some operations on them.
p=root; ➢ A linked list always contains a pointer variable START which stores
while(i<loc) the address of the first node of the list.
{

17
CS8251-PROGRAMMING IN C

➢ The end of the list is marked by storing NULL or -1 in the NEXT Case 3 The node after the given node is deleted.
field of the last node. When we delete a node from the linked list, we have to free the
➢ For traversing the linked list, we also make use of another pointer memory occupied by that node.
variable PTR which points to the node that is currently being
accessed. Eg:\\ Delete first, middle and last node

Eg: void delete()


void traverse() {
{ struct node*temp;
struct node*temp; int loc;
temp=(struct node*)malloc(sizeof(struct node)); printf(“ enter the loc to be deleted “);
printf(“Enter the node data”); scanf(“%d”,&loc);
scanf(“%d”,&temp->data); if(loc>length())
temp->next=NULL; {
if(root==NULL) printf(“ Invalid location”);
{ }
root=temp; else if(loc==1)// deleting first node
} {
else temp=root;
{ root=temp->next;
struct node*p; temp->next=NULL;
p=root; free(temp);
while(p->next!=NULL) }
{ else // deleting specified position as well as last node
p=p->next; {
} struct node *p=root;
p->next=temp; int=1;
} while(i<loc-1)
} {
Deleting a node from a linked list p=p->next;
i++;
Case 1 The first node is deleted. }
Case 2 The last node is deleted. q=p->next;

18
CS8251-PROGRAMMING IN C

p->next=q->next;
q->next=NULL;
free(q);
}
void display()
{
struct node*temp;
temp=root;
if(temp==NULL)
{
printf(“ No nodes in the list “);
}
else
{
while(temp!=NULL)
{
printf(“%d”,temp->data);
temp=temp->next;
}
}

19

You might also like