PSPC Unit 4 Notes
PSPC Unit 4 Notes
PSPC Unit 4 Notes
UNIT IV STRUCTURES
Structure - Nested structures – Pointer and Structures – Array of structures –
Example Program using structures and pointers – Self referential structures –
Dynamic memory allocation - Singly linked list - typedef.
STRUCTURES:
- Structure is a collection of various data types shares a common name.
- It is a user defined data type.
- Each element in a C structure is called member.
Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Arrays Structures
Collection of similar data types. Collection of different data types.
Static memory allocation is done in arrays Dynamic memory allocation is done in structures.
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to
an array element. access members of structures
Array is a pointer to its first element. Structure is not a pointer.
Array is a derived data type. Structure is a user defined data type.
Accessing array element takes less time Accessing structure member takes more time.
It has no keywords. It uses keyword “struct”
Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:
Syntax: Example:
struct tag_name struct student
{ {
datatype member 1; char name[10];
datatype member 2; int roll_no;
datatype member n; float percentage;
}; };
Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.
1
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
2
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
NESTED STRUCTURE:
A structure with in a structure is called nested structure.
The elements of nested structure are accessed using dot (.) operator.
Syntax:
Example:
structure tagname_1
struct Employee
{
{
data_type member1;
char ename[20];
data_type member2;
int empid;
data_type member3;
int salary;
..
struct date
member n;
{
structure tagname_2
int day;
{
int month;
data_type member_1;
int year;
data_type member_2;
}doj;
data_type member_3;
... }emp;
member_n;
} var1;
} var2;
3
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
Syntax:
4
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
ARRAY OF STRUCTURES:
s[0].name : refers to the name member of the 0th element of the array.
s[0].roll_no : refers to the roll_no member of the 0th element of the array.
s[0].marks : refers to the marks member of the 0th element of the array.
5
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
{
struct student s[5]; Enter details of student 3
int i; Enter name: mahesh
for(i = 0; i < MAX; i++) Enter roll no: 1003
{ Enter marks: 56.9
printf("\n Enter details of student %d\n\n", i+1);
Enter details of student 4
printf("Enter name: "); Enter name: rini
scanf("%s", s[i].name); Enter roll no: 1004
Enter marks: 96
printf("Enter roll no: ");
scanf("%d", &s[i].roll_no); Enter details of student 5
Enter name: ram
printf("Enter marks: "); Enter roll no: 1005
scanf("%f", &s[i].marks); Enter marks: 36.9
}
printf("\n");
printf("Name\tRoll no\tMarks\n");
for(i = 0; i < MAX; i++ )
{
printf("%s\t%d\t%.2f\n",
s[i].name, s[i].roll_no, s[i].marks);
}
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.
6
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
{
printf("Size of book structure is :%d",sizeof(b1.bookname));
}
Output:
Size of book structure is :84
7
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
Example:
Displaying book details using pointer to a structure:
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
float price;
};
int main()
{
struct book b1; // structure variable declaration
8
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
9
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
malloc()
calloc()
realloc()
free()
(i)malloc() function:
- malloc() stands for "memory allocation".
- malloc () function is used to allocate space in memory during the execution of the
program.
- This function reserves a block of memory of the given size and returns a pointer of
type void (that is to be typecasted)
Syntax:
Pointer_variable= (type_cast*) malloc(Size_in _bytes)
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
Here, 50 represents the total size to be allocated depending upon 16 bit or 32 bit processor.
Hence given, sizeof() function irrespective of 2 byte or 4 byte integer
- If it fails to allocate enough space as specified, it returns a NULLpointer.
- malloc () does not initialize the memory allocated during execution. It carries garbage
value.
Program (to copy a string to allocated memory using malloc()):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char*)malloc( 20 * sizeof(char) ); // memory is allocated dynamically
if( ptr== NULL )
{
printf("Couldn't able to allocate requested memory\n");
10
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning
(ii)calloc() function:
The name calloc() stands for "contiguous allocation".(continues)
calloc() is another memory allocation function that is used for allocating memory at
runtime.
This statement will allocate contiguous space in memory for an array of n elements.
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
calloc () initializes the allocated memory to zero. But, malloc() does not.
If it fails to allocate enough space as specified, it returns a NULL pointer.
Syntax:
Pointer_variable= (type_cast*) calloc(n, element_size)
Example:
float *y;
y= (float*) calloc(25, sizeof(float));
Note:
This statement allocates contiguous space in memory to store 25 elements each of size of
float( i.e, 4 bytes)
11
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
(iii) realloc():
- realloc() used to change the memory size that is already allocated using malloc()
and calloc() functions.
Syntax:
ptr = realloc(ptr, newsize); //ptr is reallocated with size of newsize.
Example:
int *x;
x = (int*)malloc(50 * sizeof(int));
x = (int*)realloc(x,100); //allocated a new memory to variable x
12
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
free()
- free() to release the space that are allocated using memory by malloc (), calloc (),
realloc () functions .
- It returns the memory to the system.
Syntax:
free(pointer_variable);
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
free(x); //releases the memory allocated to variable x
Output:
Dynamically allocated memory content : good morning
Resized memory : can store 100 characters
13
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
14
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
A structure that contains at least one pointers to a structure as its member along with other
members is known as self-referential structure.
The above illustrated self referential structure prototype describes one node that comprises of
two logical segments.
One segment stores data and the other segment is a pointer indicating where the next element
is present.
Several such inter-connected nodes create a chain of structures(Linked List).
15
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
16
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
2. Deleting a node:
If node to be deleted is root, simply delete it.
To delete a middle node, we must have pointer to the node previous to the node to be
deleted. So if positions is not zero, we run a loop position-1 times and get pointer to the
previous node.
Advantages of linked list over arrays:
1) list uses Dynamic size whereas, array uses static size.
2) Easy to insert/delete element in list where as array requires shifting of elements.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from
the first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
17
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
create(); 10 20 30 35
i++; 40
} Enter your option
printf("enter ur option=\n"); 2
printf("1.insert\t 2.delete \t 3.display\t 4.exit\n"); enter the position to delete:
do 2
{
scanf("%d",&opt); Enter your option
switch(opt) 3
{ List elements are:
case 1: 10 30 35 40
insert(); Enter your option
count++; 4
break;
case 2:
delet();
count--;
if(count==0)
{
printf("\n List empty\n");
}
break;
case 3:
printf("List elements are:\n");
display();
break;
}
printf("\nEnter your option\n");
}while(opt!=4);
}
void create()
{
if(p==NULL)
{
p=(LIST*)malloc(sizeof(LIST));
printf("Enter the element\n");
scanf("%d",&p->no);
p->next=NULL;
h=p;
18
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
}
else
{
t=(LIST*)malloc(sizeof(LIST));
printf("enter the element");
scanf("%d",&t->no);
t->next=NULL;
p->next=t;
p=t;
}
}
void insert()
{
t=h;
p=(LIST*)malloc(sizeof(LIST));
printf("enter the element to be inserted\n");
scanf("%d",&p->no);
printf("enter the position to insert\n");
scanf("%d",&pos);
if(pos==1)
{
h=p;
h->next=t;
}
else
{
for(j=1;j<(pos-1);j++){
t=t->next;
}
p->next=t->next;
t->next=p;
t=p;
}
}
void delet()
{
printf("enter the position to delete:\n");
scanf("%d",&pos);
19
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
if(pos==1)
{
h=h->next;
}
else
{
t=h;
for(j=1;j<(pos-1);j++){
t=t->next;
}
pt=t->next->next;
free(t->next);
t->next=pt;
}
}
void display()
{
t=h;
while(t->next!=NULL)
{
printf("\t%d",t->no);
t=t->next;
}
printf("\t %d\t",t->no);
}
TYPEDEF:
- Typedef keyword is used to create a user defined name for existing data type.
- Generally typedef are use to create an alias name (nickname).
Syntax:
typedef datatype alias_name;
typedef int intdata;
20
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
21
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
Program:
#include <stdio.h> ***MAIN MENU***
typedef struct distance 1. Read the distances
{ 2. Display the distances
3. Add the distances
int kms; 4. Subtract the distances
int metres; 5. EXIT
} DISTANCE; // structure variable Enter your option: 1
DISTANCE add_distance (DISTANCE, DISTANCE);
DISTANCE subtract_distance(DISTANCE,DISTANCE); Enter the first distance in kms
DISTANCE dl, d2, d3, d4; and metres:
3
320
int main()
{ Enter the second distancekms
int option; and metres:
do 5
{ 100
printf("\n ***MAIN MENU***");
***MAIN MENU***
printf ("\n 1. Read the distances ");
1. Read the distances
printf ("\n 2. Display the distances"); 2. Display the distances
printf ("\n 3. Add the distances "); 3. Add the distances
printf ("\n 4. Subtract the distances"); 4. Subtract the distances
printf ("\n 5. EXIT"); 5. EXIT
printf ("\n Enter your option: "); Enter your option: 2
scanf("%d", &option);
The first distance is: 3 kms
switch(option) 320 metres
{ The second distance is: 5 kms
case 1: 100 metres
printf("\n Enter the first distance in kms and metres: ***MAIN MENU***
"); 1. Read the distances
scanf ("%d %d", &dl .kms, &dl .metres); 2. Display the distances
3. Add the distances
printf("\n Enter the second distancekms and metres:
4. Subtract the distances
"); 5. EXIT
scanf ("%d %d" , &d2 .kms, &d2 .metres); Enter your option: 3
break;
case 2: The sum of two distances is: 8
printf("\n The first distance is: %d kms %d metres " kms 420 metres
, dl.kms, dl.metres); ***MAIN MENU***
1. Read the distances
printf("\n The second distance is: %d kms %d
2. Display the distances
metres " , d2 .kms, d2 .metres); 3. Add the distances
22
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
23
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
else
{
sub.metres = d2.metres - dl. metres;
sub.kms = d2.kms - dl.kms;
}
if(sub.metres < 0)
{
sub.kms = sub.kms - 1;
sub.metres = sub.metres + 1000;
}
return sub;
}
24
23ES1101 PROBLEM SOLVING USING C PROGRAMMING Unit 4
if ( c.img >= 0 )
printf("Difference of two complx no = %d + %di",c.real, c.img);
else
printf("Difference of two complex no = %d %di", c.real, c.img);
}
printf("\nPress any key to enter choice again...\n");
}
}
25