Aut - Unit 4
Aut - Unit 4
Basics of structures-structure data types, type definition, accessing structures, Structure operations,
Complex structures-nested structures, structures containing arrays, Array of structures, Structures and
Functions, Unions. Pointers: Understanding Computer Memory –Memory Management-Dynamic
memory Allocation-Memory leaks- Introduction to Pointers – declaring Pointer Variables – Pointer
Expressions and Pointer Arithmetic – Null Pointers – Generic Pointers - Passing Arguments to Functions
using Pointer – Pointer and Arrays –Use of pointers in self-referential structures, notion of linked list.
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
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to access members of
an array element. structures
Accessing array element takes less time Accessing structure member takes more time.
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:
{ {
float percentage;
datatype member n; };
};
Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.
Syntax: Example:
1
struct tag_name
{ struct student
datatype member 1; {
‘ float percentage;
‘ }
struct book s1,s2;
datatype member n;
2
NESTED STRUCTURE:
A structure with in a structure is called nested structure.
The elements of nested structure are accessed using dot (.) operator.
Syntax:
structure tagname_1 Example:
{ struct Employee
data_type member1; {
data_type member2; char ename[20];
data_type member3; int empid;
.. int salary;
member n; struct date
structure tagname_2 {
{ int day;
data_type member_1; int month;
data_type member_2; int year;
data_type member_3; }doj;
... }emp;
member_n;
} var1;
} var2;
Syntax:
3
Program to display employee details using nested structure: Output:
#include <stdio.h>
struct Employee Employee Name : ramya
{
char ename[20];
int empid; Employee ID : 1001
int salary;
struct date Employee Salary : 25000
{
int day; Employee DOJ : 25/9/1988
int month;
int year;
}doj;
}emp;
int main()
{
struct Employee emp={"ramya",1001,25000,{25,9,1988}};
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee ID : %d",emp.empid);
printf("\nEmployee Salary : %d",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.day, emp.doj.month, emp.doj.year);
return 0;
}
ARRAY OF STRUCTURES:
4
- Here s is an array of 5 elements where each element is of type struct student.
- We can use s to store 5 structure variables of type struct student.
- To access individual elements we will use subscript notation ([]) and to access the members of each element we will use dot (.)
operator as usual.
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.
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);
5
}
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.
6
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
struct book *ptr; // pointer variable declaration
ptr=&b1; // pointer variable initialization
printf("enter the bookid\n");
scanf("%d",&ptr->bookid);
printf("enter the book name\n");
scanf("%s",ptr->bookname);
printf("enter author\n");
7
scanf("%s",&ptr->author);
printf("Enter price");
scanf("%f",&ptr->price);
printf("book details are\n: %d\t %s\t %s\t %f\n\n",ptr->bookid,ptr->bookname,ptr->author,ptr->price);
}
Output:
enter the bookid
1001
enter the book name
python
enter author
Rossum
Enter price 450
book details are
1001 python Rossum 450.000000
(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.
8
- 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");
}
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.
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)
9
{
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
(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
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
10
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content : %s\n", ptr );
ptr=realloc(ptr,100*sizeof(char));
strcpy( ptr,"can store 100 characters");
printf("Resized memory : %s\n", ptr);
free(ptr);
}
Output:
Dynamically allocated memory content : good morning
Resized memory : can store 100 characters
C Program to generate Salary Slip of employee( Dynamic memory allocation for Structure using pointers):
#include <stdio.h> Output:
#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{
int i,n; Enter Others1000
struct employee *ptr;
printf("enter the number of employee"); Enter pf500
scanf("%d",&n);
ptr=(struct employee*)malloc(n * sizeof(struct employee)); Enter IT1000
for(i=0;i<n;i++) enter the nameraja
{ Enter Basic Salary (RS): 25000
printf("enter the name");
scanf("%s",(ptr+i)->name); Enter Hra1000
printf("Enter Basic Salary (RS): ");
scanf("%d",&(ptr+i)->basic); Enter da1000
printf("\nEnter Hra");
scanf("%d",&(ptr+i)->hra); Enter TA1000
printf("\nEnter da");
scanf("%d",&(ptr+i)->da); Enter Others500
printf("\n Enter TA");
scanf("%d",&(ptr+i)->ta); Enter pf1000
printf("\nEnter Others");
scanf("%d",&(ptr+i)->others); Enter IT1500
printf("\nEnter pf");
scanf("%d",&(ptr+i)->pf); Name is ravi Net Salary is:RS 13500
printf("\nEnter IT");
scanf("%d",&(ptr+i)->it); Name is raja Net Salary is:RS 26000
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).
⬧ Operations like insertion or deletion of nodes in a self- referential structure involve simple and straight forward alteration of
pointers.
Singly Linked List(Linear List):
● In linked list, elements are not stored at contiguous location; the elements are linked using pointers.
● A linked list is represented by a pointer to the first node of the linked list.
● The first node is called head. If the linked list is empty, then value of head is NULL.
Each node in a list consists of at least two parts:
1) data
2) pointer to the next node
In C, we can represent a node using structures.
● Below is an example of a linked list node with an integer data.
Operations on Linked List:
1. Inserting a node in linked list:
A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.
i) Insertion at the front of linked list:
When a new node is added at the front, it becomes the header of the list. Here, Node E is added at the front. Hence E becomes the
header node and not A.
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.
Program to insert, delete and display the elements in singly linked list Output:
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)
{
14
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);
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;
1. C program to read, display, add, and subtract two distances. Distance must bedefined Output
using kms and meters using structures.(typedef)
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 and metres:
DISTANCE dl, d2, d3, d4; 3
320
int main() Enter the second distancekms and metres:
{ 5
int option; 100
do
{ ***MAIN MENU***
printf("\n ***MAIN MENU***"); 1. Read the distances
2. Display the distances
printf ("\n 1. Read the distances ");
3. Add the distances
printf ("\n 2. Display the distances"); 4. Subtract the distances
printf ("\n 3. Add the distances "); 5. EXIT
printf ("\n 4. Subtract the distances"); Enter your option: 2
printf ("\n 5. EXIT");
printf ("\n Enter your option: "); The first distance is: 3 kms 320 metres
The second distance is: 5 kms 100 metres
scanf("%d", &option);
***MAIN MENU***
switch(option) 1. Read the distances
{ 2. Display the distances
case 1: 3. Add the distances
printf("\n Enter the first distance in kms and metres: "); 4. Subtract the distances
16
scanf ("%d %d", &dl .kms, &dl .metres); 5. EXIT
printf("\n Enter the second distancekms and metres: "); Enter your option: 3
scanf ("%d %d" , &d2 .kms, &d2 .metres);
The sum of two distances is: 8 kms 420 metres
break;
***MAIN MENU***
case 2: 1. Read the distances
printf("\n The first distance is: %d kms %d metres " , dl.kms, dl.metres); 2. Display the distances
printf("\n The second distance is: %d kms %d metres " , d2 .kms, d2 .metres); 3. Add the distances
break; 4. Subtract the distances
case 3: 5. EXIT
d3 = add_distance(dl, d2); Enter your option: 4
printf("\n The sum of two distances is: %d kms %d metres", d3.kms, d3.metres);
The difference between two distances is: 1
break; kms 780 metres
case 4: ***MAIN MENU***
d4 = subtract_distance(dl, d2); 1. Read the distances
printf("\n The difference between two distances is: %d kms %d metres ", d4.kms, 2. Display the distances
d4 .metres); 3. Add the distances
break; 4. Subtract the distances
5. EXIT
}
Enter your option: 5
}
while(option != 5);
{
return 0;
}
}
DISTANCE add_distance(DISTANCE dl, DISTANCE d2)
{
DISTANCE sum;
sum.metres = dl.metres + d2. metres;
sum.kms = dl.kms + d2.kms;
if(sum.metres >= 1000)
{
sum.metres = sum.metres%1000;
sum.kms += 1;
}
return sum;
}
DISTANCE subtract_distance(DISTANCE dl,DISTANCE d2)
{
DISTANCE sub;
if(dl.kms > d2.kms)
{
sub.metres = dl.metres - d2. metres;
sub.kms = dl.kms - d2.kms;
}
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;
}
17
Output
2.C program to add, subtract two complex numbers using structure.
if ( c.img >= 0 )
printf("Sum of two complex numbers = %d + %di", c.real, c.img);
else
printf("Sum of two complex numbers = %d %di",c.real,c.img);
}
else if ( choice == 2 )
{
c.real = a.real - b.real;
c.img = a.img - b.img;
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");
}
}
3.Define a structure called student that would contain name, regno and marks of five
subjects and percentage. Write a C program to read the details of name, regno and marks of five subjects for 30 students and calculate
the percentage and display the name, regno, marks of 30 subjects and percentage of each student.( AssignmentQuestion)
18
Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting of names –
Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two numbers and changing the value of a variable
using pass by reference.
POINTERS:
❖ Pointer reduces the code and improves the performance, because it direct access the address of variable.
❖ Pointers can be used to return multiple values from a function via arguments.
Declaration of a variable:
Pointer_variable=&variable_name; p=&a;
19
Function Output
printf(“%d”,a); 50
printf(“%u”,&a); 1001
printf(“%u”,p); 1001
printf(“%u”,&p); 2047
printf(“%d”,*p); 50
Pointer Operators:
Simply, To create pointer to a variable we use “*” operator and to find the address of variable we use “&” operator. Eg,
20
We can perform arithmetic operations on a pointer just like we can on numeric value.
There are four arithmetic operators that can be used on pointers:
++,
--,
+,
-
Arithmetic operations that can be performed on value and address are given below.
Example:
Note:
All the arithmetic operations can be performed on values. But only subtraction, increment and decrement can be performed on
address.
Addition:
⬧ We cannot add two pointers.
⬧ This is because pointers contain addresses, adding two addresses makes no sense, because you have no idea what address would
address it would point to. It may go beyond the limit also. Eg, p1+p2
Subtraction:
⬧ We can subtract two pointers.
⬧ This is because difference between two pointers gives the number of elements of its data type that can be stored between the two
pointers. Eg, p2-p1
Increment:
⬧ If the pointer p1 points to an integer whose address is 1000 , after this increment operation, p1 will point to the location 1002
because each time p1 is incremented, it will point to the next integer location which is 2 bytes next to the current location for
integer data type.
⬧ If p1 points to a character whose address is 1000, then the above operation will point to the location 1001 because the next
character will be available at 1001. Eg, p1++;
Decrement:
⬧ Similarly, depending upon the size of data type, the position is decremented Eg, p1--;
Operators Arithmetic operators on value Arithmetic operators on address
Example
Subtraction(-) *p1-*p2 p2-p1(legal)
5-6=-1 1002-1000=1(2 bytes of data)
21
Program for pointer arithmetic Output:
#include <stdio.h> p1 = 2680014
int main() p2 = 2680012
{ *p1+*p2 = 15
int a = 5, b = 10, c = 0; p1-p2 = 1
int *p1; // pointer declaration p1++ = 2680018
int *p2; p2-- = 26800010
int *p3;
p1 = &a; // pointer initialization
p2 = &b;
printf("p1 = %u\n", p1); //printing the address of a
printf("p2 = %u\n", p2);//printing the address of b
c = *p1+*p2;
printf("*p1+*p2 = %d\n", c);
p3 = p1-p2;
printf("p1 - p2 = %u\n", p3);
p1++;
printf("p1++ = %u\n", p1);
p2--;
printf("p2-- = %u\n", p2);
22
- Pointer to array simply points to base address of an array
- Base address is nothing but starting address ( address of 0th element).
- The address (memory location) of next element is dependent on size of data types( 2 bytes or 4 bytes for integer depending on the
compiler ).
Pointer initialization:
int a[5]={10,20,30,40,50};
int *p;
p=a;
here, pointer variable ‘p’ points only to the base address(starting address) of array.
So, p=a ;
is same as p=&a[0];
(ii)Array of Pointers:
- Array of pointers is the Collection of pointers to hold different addresses
Syntax:
datatype *array_name[size];
Example:
int *a[5] ;
Here, a is an array of 5 integer pointers. (i,e), this array can hold the address of 5 integer variables.
In other words we can assign 5 pointer variables of type pointer to int to the elements of this array.
Program to print elements using array of pointers: Description:
#include<stdio.h>
int main()
{
int *arr[3];
int a = 10, b = 20, c = 30, i;
arr[0] = &a; // address of variable a to the 0th element of the of the
array
arr[1] = &b;
arr[2] = &c;
for(i = 0; i < 3; i++)
{ arr[i] gives the address of ith element of the array.
printf("Address = %d\t Value = %d\n", arr[i], *arr[i]); So arr[0] returns address of variable a, arr[1]returns address
} of b and so on.
23
return 0; To get the value at address use indirection operator (*).
} So *arr[0] gives value at address[0], Similarly *arr[1] gives the
Output: value at address arr[1] and so on.
Address = 37814036 Value = 10
Address = 37814032 Value = 20
Address = 37814028 Value = 30
TYPES OF POINTERS:
NULL pointer:
24
1. When a null pointer is compared with a pointer to any object the result of comparison is always false.
2. Two null pointers always compares equal.
3. Dereferencing null pointer leads to error.
Void pointer:
❖ Void pointer is a general purpose pointer that can point to any data type
❖ The pointer used to point different data types is called void data type.
❖ If we assign address of char data type to void pointer it will become char Pointer, if int data type then int pointer and so
on. Any pointer type is convertible to a void pointer hence it can point to any value.
NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
25
Declaration:
int **ptr; // declaring double pointers
Initialization:
int a= 78;
int *ptr2; // pointer for variable a
int **ptr1; // double pointer for ptr2
ptr2 = &a; // storing address of a in ptr2
ptr1 = &ptr2;
Call by Value:
26
int a=10; Note: Value is not modified in main function.
printf("Before function call x=%d \n", a);
my_change(a); //passing value in function
printf("After function call x=%d \n",a);
return 0;
}
void my_change(int num)
{
num=num+5;
printf("changed value is x=%d \n",num);
}
⬧ Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
⬧ Hence, value changed inside the function, is reflected inside as well as outside the function.
Actual and formal arguments will be created in different Actual and formal arguments will be created in same memory
memory location location
Slow processing because new address are created. Fast because existing address are used.
Illustrative Program( Swapping of two numbers and changing the value of a variable using pass by value and reference)
Swapping of 2 vaues(Exchanging) using call by reference: Swapping of 2 values(Exchanging) using call by Reference:
#include<stdio.h> #include<stdio.h>
void swap(int, int); void swap(int *x, int*y);
int main() int main()
{ {
int a=5,b=10; int a=5,b=10;
printf("Before Swap values of a and b is %d %d\n", a, b); printf("Before Swap values of a and b is %d %d\n", a, b);
swap(a, b); swap(&a, &b);
return(0); printf("After Swap values of a and b is %d %d\n", a, b);
} return(0);
}
void swap(int x, int y)
{ void swap(int *x, int *y)
27
int temp; {
temp = x; int temp;
x = y; temp = *x;
y = temp; *x = *y;
printf("after Swap values of a and b is %d %d\n", x, y); *y = temp;
} return;
Output: }
before swap,value of an and b is 5 10
after swap,value of a and b is 10 5 Output:
Before Swap values of a and b is 5 10
After Swap values of a and b is 10 5
28