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

Unit IV Structures

Uploaded by

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

Unit IV Structures

Uploaded by

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

UNIT IV STRUCTURES

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

Collection of similar data types. Collection of different data types.

Static memory allocation is done in arrays Dynamic memoryallocation is done in structures.

It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to access members of
an arrayelement. 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 Accessingstructuremembertakesmore 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 member2; int roll_no;

float percentage;

datatype membern; };

};

Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.

2. Declaring structure variable

Syntax: Example:

1
struct tag_name

{ struct student

datatype member1; {

datatype member2; char name[10];

datatype member3; int roll_no;


‘ float percentage;
‘ }
struct book s1,s2;
datatype membern;

} variable1, variable2,……. variable n; Note:


Structure variable can be declared within the structure definition or
in the main function.

3. Initializing the members of structure:


Initialization can be done in 2 ways.
 Compile time initialization:
- uses assignment operator(=) to initialize values to the members of structure.
Example:
struct student s1={“ramya”,1001,45.8};
struct student s2={“anitha”,1002,89.6};
 Run time initialization:
- uses scanf function to read the input from the user.
Example:
printf("enter s1 student details"); scanf("%s%d
%f",s1.name,&s1.roll_no,&s1.percentage); printf("enter s2
student details"); scanf("%s%d
%f",s2.name,&s2.roll_no,&s2.percentage);

4. Accessing the members of the structure:


- Members can be accessed using .operator (dot). Also pointer operator is used(->)
Syntax:
structure_variable_name . member_name;
Example:
s1.name // to access name of s1
s2.percentage // to access percentage of
s2
Program to print student details( accessing member using .dot operator): Output:
#include<stdio.h> Enter rollno, name , percentage
struct student 1001
{ ramya
int roll; 96.8
char name[10]; Student details are:
float percentage; ROLL_NO=1001 NAME=ramya
}s1; PERCENTAGE=96.80000
int main()
{
printf("Enter rollno, name , percentage\n");
scanf("%d%s%f", &s1.roll, s1.name, &s1.percentage);
printf("Student details are:\n");
printf ("ROLL_NO=%d\n NAME=%s\n PERCENTAGE=%f\n", s1.roll, s1.name,
s1.percentage);
return(0);
}

2
NESTED STRUCTURE:

3
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:

outrstructurevariable . innerstructure variable . innerstructuremember

To Access the Nested members,

Accessingmonth Field: emp1.doj.month

AccessingdayField : emp1.doj.day

Accessingyear Field : emp1.doj.year

4
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:

- Array of structures is nothing but collection of structures.


- Declaring an array of structure is same as declaring an array of fundamental types.
- This is also called as structure array in c.

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

Accessing members of array structure:


s[0] : points to the 0th element of the array.
s[1] : points to the 1st element of the array.

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.

Program to print 5 student details using array of structures: Output:


#include<stdio.h>
#define MAX 5 Enter details of student 1
struct student Enter name: ravi
{ Enter roll no: 1005
char name[20]; Enter marks: 89.6
int roll_no, i;
float marks; Enter details of student 2
}; Enter name: priya
int main() Enter roll no: 1002
{ Enter marks: 89.6
struct student s[5];
int i; Enter details of student 3
for(i = 0; i < MAX; i++) Enter name: mahesh
{ Enter roll no: 1003
printf("\n Enter details of student %d\n\n", i+1); Enter marks: 56.9

printf("Enter name: "); Enter details of student 4


scanf("%s", s[i].name); Enter name: rini
Enter roll no: 1004
printf("Enter roll no: "); Enter marks: 96
scanf("%d", &s[i].roll_no);
Enter details of student 5
printf("Enter marks: "); Enter name: ram
scanf("%f", &s[i].marks); Enter roll no: 1005
} 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);
}

6
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.

How To Find the Size of Structure?


- sizeof() function is used to find the size of structure.
- sizeof can be applied to any data-type, including primitive types such as integer and floating-point
types, pointer types, or compound datatypes such as Structure, union etc.Syntax:
Example: (Sizeof() for structure)
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
};
int main()
{
printf("Size of book structure is :%d",sizeof(b1.bookname));
}
Output:
Size of book structure is :84

POINTER AND STRUCTURE:


C structure can be accessed in 2 ways in a C program. They are,
(i) Using normal structure variable
(ii) Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and
Arrow (->) is used to access the data using pointer variable.
Syntax: Example:
struct name struct product
{ {
member1; int prod_id;
member2; char prod_name[20];
. float price;
}; };
struct name *ptr; struct product *p1;

Difference between normal structure variable and pointer variable:

7
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"); scanf("%s",&ptr-
8
>author);

9
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

DYNAMIC MEMORY ALLOCATION:


Why do we need to go for Dynamic Memory Allocation?
 We know, an array is uses static memory allocation technique because, the size of the array is fixed. So we cannot increase or
decrease the size of the array once size is declared.
 Hence, the array we declared may be insufficient or sometimes size may be more than what we required.
 To solve this issue, we can allocate memory dynamically.
Dynamic Memory Allocation:
 The process of allocating memory during program execution is called dynamic memory allocation.
 It allows us to manually handle memory space for our program.
There are 4 library functions defined under <stdlib.h> which can be used for dynamic memory allocation.
They are,
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>

10
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.
 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)

Program: (To copy a string to allocated memory using calloc() ):


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *ptr;
ptr = (char*)calloc( 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

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

Difference between malloc() and calloc():

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

Program: ( To copy a string to allocated memory using realloc())


#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 : %s\n", ptr );
ptr=realloc(ptr,100*sizeof(char));
strcpy( ptr,"can store 100 characters");
printf("Resized memory : %s\n", ptr);
free(ptr);
}

12
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 Enter IT1000
employee)); 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); printf("\ Enter Others500
n Enter TA");
scanf("%d",&(ptr+i)->ta); printf("\ Enter pf1000
nEnter Others");
scanf("%d",&(ptr+i)->others); Enter IT1500
printf("\nEnter pf");
scanf("%d",&(ptr+i)->pf); printf("\ Name is ravi Net Salary is:RS 13500
nEnter IT"); scanf("%d",&(ptr+i)-
>it); Name is raja Net Salary is:RS 26000

//calculate net salary


(ptr+i)->net_salary = (ptr+i)->basic + (ptr+i)->da + (ptr+i)->hra + (ptr+i)->ta
+ (ptr+i)->others - ((ptr+i)->pf+(ptr+i)->it);
}
//printing Net salary for(i=0;i<n;i+
+)
{
printf("\n Name is %s",(ptr+i)->name);
printf("\t Net Salary is:RS %d\n",(ptr+i)->net_salary);
}
return(0);

SELF REFERENTIAL STRUCTURES:

A structure that contains at least one pointers to a structure as its member along with other members is known as self-referential structure.

13
Pointer variable declaration in structure Self-referential structure declaration
struct name { struct name {
member 1; member 1;
member 2; member 2;
... ...
member n; struct name *pointer;
}; };
struct name *pointer;

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

 A self-referential structure can dynamically be expanded or contracted.


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

ii) Inserting node at a given position

iii) Inserting at the End

14
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:

Program : enter the number of nodes


#include<stdio.h> 4
#include<stdlib.h> Enter the element
#define NULL 0 10
typedef struct list enter the element20
{ enter the element30
int no; enter the element40
struct list *next; enter ur option=
}LIST; 1.insert 2.delete 3.display 4.exit
3
LIST *p,*t,*h,*y,*ptr,*pt;
List elements are:
void create(void);
10 20 30 40
void insert(void);
Enter your option
void delet(void);
1
void display(void); enter the element to be inserted
int j,pos,k=1;count; 35
void main() enter the position to insert
{ 4
int n,i=1,opt;
printf("%d",sizeof(LIST)); Enter your option
printf("enter the number of nodes\n"); 3
scanf("%d",&n); List elements are:
count=n; 10 20 30 35 40
while(i<=n) Enter your option
{ 2
create(); enter the position to delete:
i++; 2
}
printf("enter ur option=\n"); Enter your option
printf("1.insert\t 2.delete \t 3.display\t 4.exit\n"); 3
do List elements are:
{ 10 30 35 40
scanf("%d",&opt); Enter your option
4
switch(opt)
{
case 1:
insert();

15
count++;
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;
}
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;

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

Example: (Use of typedef on integer data type)


Program: - In this program, Intdata is an user defined
#include<stdio.h>
typedef int Intdata; // Intdata is alias name of int name or alias name for an integer data type.
int main()
{ - All properties of the integer will be applied
int a=10;
Intdata b=20; on Intdata also.
typedef Intdata Integerdata; // Integerdata is again alias name of Intdata
Integerdata s; - Integerdata is an alias name to existing user
s=a+b;
printf("\n Sum:= %d",s); defined name called Intdata.
return(0);
}
Output:
Sum:=30

Use of typedef on structure datatype:


Program: Output:
#include<stdio.h>
typedef struct telephone

18
{
char name[20]; enter the name
int tel_no;
}t1;
anitha
int main()
{
enter the telephone number
t1 t11;
printf("enter the name");
scanf("%s",t11.name); 3216546531
printf("enter the telephone number");
scanf("%s",&t11.tel_no); Name:anitha
printf("Name:%s\n",t11.name);
printf("telephone number is:%d",t11.tel_no); telephone number :909193779
return(0);
}

Example Programs Using Pointer and Structure:

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 Enter the first distance in kms and metres:
subtract_distance(DISTANCE,DISTANCE); 3
320
DISTANCE dl, d2, d3, d4;
Enter the second distancekms and metres:
int main() 5
{ 100
int option;
do ***MAIN MENU***
{ 1. Read the distances
2. Display the distances
printf("\n ***MAIN MENU***");
3. Add the distances
printf ("\n 1. Read the distances "); 4. Subtract the distances
printf ("\n 2. Display the distances"); 5. EXIT
printf ("\n 3. Add the distances "); Enter your option: 2
printf ("\n 4. Subtract the distances");
printf ("\n 5. EXIT"); The first distance is: 3 kms 320 metres
printf ("\n Enter your option: "); The second distance is: 5 kms 100 metres
***MAIN MENU***
scanf("%d", &option); 1. Read the distances
switch(option) 2. Display the distances
{ 3. Add the distances
case 1: 4. Subtract the distances
printf("\n Enter the first distance in kms and metres: "); 5. EXIT
scanf ("%d %d", &dl .kms, &dl .metres); Enter your option: 3
printf("\n Enter the second distancekms and metres: ");
The sum of two distances is: 8 kms 420 metres
scanf ("%d %d" , &d2 .kms, &d2 .metres); ***MAIN MENU***
break; 1. Read the distances
case 2: 2. Display the distances
printf("\n The first distance is: %d kms %d metres " , dl.kms, dl.metres); printf("\ 3. Add the distances
n The second distance is: %d kms %d metres " , d2 .kms, d2 .metres); 4. Subtract the distances
break; 5. EXIT
Enter your option: 4
case 3:
d3 = add_distance(dl, d2); The difference between two distances is: 1
19
printf("\n The sum of two distances is: %d kms %d metres", d3.kms, d3.metres);

break; kms 780 metres


case 4: ***MAIN MENU***
d4 = subtract_distance(dl, d2); 1. Read the distances
2. Display the distances
printf("\n The difference between two distances is: %d kms %d metres ", d4.kms,
3. Add the distances
d4 .metres); 4. Subtract the distances
break; 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;
}

2.C program to add, subtract two complex numbers using structure. Output
Program: Press 1 to add two complex numbers
#include <stdio.h> Press 2 to subtract two complex numbers
#include <stdlib.h> Press 3 to exit
struct complex Enter your choice
{ 1
int real, img; Enter a and b where a + ib is the first complex
}a,b,c; // Structure Variable number.
int main() a=3
{ b=5
Enter c and d where c + id is the second
20
int choice; complex number.
while(1)

{ c=2
printf("Press 1 to add two complex numbers\n"); d=6
printf("Press 2 to subtract two complex numbers\n"); Sum of two complex numbers = 5 + 11i
printf("Press 3 to exit\n"); Press any key to enter choice again...
printf("Enter your choice\n");
scanf("%d",&choice); Press 1 to add two complex numbers
if( choice == 3) Press 2 to subtract two complex numbers
{ Press 3 to exit
exit(0); Enter your choice
} 2
if(choice >= 1 && choice <= 2) Enter a and b where a + ib is the first complex
{ number.
printf("Enter a and b where a + ib is the 1st complex number."); a=1
printf("\na = "); b=1
scanf("%d", &a.real); Enter c and d where c + id is the second
printf("b = "); complex number.
scanf("%d", &a.img); c=2
printf("Enter c and d where c + id is the 2nd complex number."); d=1
printf("\nc = "); Difference of two complex numbers = -1 + 0i
scanf("%d", &b.real); Press any key to enter choice again...
printf("d = "); Press 1 to add two complex numbers
scanf("%d", &b.img); Press 2 to subtract two complex numbers
} Press 3 to exit
if ( choice == 1 ) Enter your choice
{ 3
c.real = a.real + b.real;
c.img = a.img + b.img;

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)

21
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:

 Apointerisavariablethatholdstheaddressofavariableor afunction.
 It is a derived data type in c language.
 Onlyaddresscanbeassignedtoapointervariable
 Pointer variable is declared with * symbol.
Advantages:
 Pointer reduces the code and improves the performance, because it direct access the address of variable.
 Pointerscanbeusedtoreturnmultiple valuesfromafunctionviaarguments.
 It allowsdynamic memory allocation.

Declarationofavariable:

For pointer declaration, we use * (asterisk symbol).


Syntax Example

datatype *pointer_variable; int *p; // pointer to integer


char *b; // pointer to character
double *p;// pointer to double
float *p;//pointer to float
Initializationofapointer:
Syntax Example

Pointer_variable=&variable_name; p=&a;

Function Output

printf(“%d”,a); 50

printf(“%u”,&a); 1001

printf(“%u”,p); 1001

printf(“%u”,&p); 2047

printf(“%d”,*p); 50

Pointer Operators:

22
Simply, To create pointer to a variable we use “*” operator and to find the address of variable we use “&” operator. Eg,

Referencing: Assigningaaddress to a pointervariable iscalled referencing.


& is a unary operator and should appear on the left side of its operand.
Example:
int a = 50;
int*p=&a;

Dereferencing: Extraction a value via pointer variable is called dereferencing.


Example:
printf(“%d”,*p);
printf(“%d”,**pptr);

Program using Referencing and Dereferencing Operator Output

#include<stdio.h> Address of a is: 37814052


int main()
{ Value of a is: 50
int a=50;
int *p;
p=&a;
printf("Address of a is: %u\n",&a);
printf("Value of a is: %d",*p);
return(0); }
POINTER ARITHMETIC:
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:

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

Increment(++) *p1++ p1++(legal)


p1+1=1002
Decrement(--) *p1-- P2--(legal)
1002-1=1000
Addition(+) *p1+*p2 p1+p2(illegal)
5+6=11 1000+1002=2002
(illegal)
Multiplication(*) (*p1)*(*p2) p1*p2(illegal)
5*6=30 1000*1002=1002000
(illegal)
/(division) (*p1)/(*p2) p1/p2(illegal)
5/6=0

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

//Below line will give ERROR


printf("p1+p2 = %d\n", p1+p2);
return 0;
}

POINTERS AND ARRAYS


- Pointer to an Array
- Array of Pointers
1. Pointer to an array
Elements in an array can be accessed using 2 methods:
(i) Standard array
(ii) Array using pointers
In array, the elements are stored in consecutive memory locations. So, it can be effectively accessed using pointers.
Example:
int a[5]={10,20,30,40,50}

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

Program to print address and value of array using pointers: Output:


int main() 37814024
{ 37814024
int a[5]={10,20,30,40,50},i; 37814024
int *p; 37814028
p=a; 10
printf("%u\n",a); 20
printf("%u\n",p); 50
printf("%u\n",&a);
printf("%u\n",a+1);
printf("%d\n",*p);
printf("%d\n",*(a+1));
printf("%d\n",*(a+4));
}
Note:
Increment operator in pointer always increments based on the size of datatype.
Eg, if base address of a is 2000, the next address is 2002 or 2004 based on datatype size(
2 bytes or 4 bytes)
Program to access elements in an array using pointers: Output:
#include<stdio.h> address of a[0]is: 37814008
int main() value of a[0]is:10
{ address of a[1]is: 37814012
int a[10]={10,20,30,40,50},i; value of a[1]is:20
int *p; address of a[2]is: 37814016
p=a; // pointer variable points to base address value of a[2]is:30
for(i=0;i<5;i++) address of a[3]is: 37814020
{ value of a[3]is:40
printf("address of a[%d]is: %u\n",i,a+i); address of a[4]is: 37814024
printf("value of a[%d]is:%d\n",i,*(a+i)); value of a[4]is:50
}
}

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

26
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

Difference between array of pointers and pointer to an array:


Array of pointers Pointer to an array
Each element of an array is an address to the memory location which It is the base address of the array
holds the data
Eg, Eg,
int *a[10]; int(*a)[10];
Each element must be accessed individually(dereferenced) Array must be dereferenced to access the value of each element.
Illustrative Program:

Sorting of names using Array of pointer:


#include<stdlib.h> Output:
#include<stdio.h> given array is
#include<string.h> ravi
int mycomp( void *a, void *b); anand
int main() chitra
{ ziya
char *arr[]={"ravi","anand","chitra","ziya"}; sorted array is
int n=sizeof(arr)/sizeof(arr[0]); anand
int i; chitra
printf("given array is\n"); ravi
for(i=0;i<n;i++) printf("%s\ ziya
n",arr[i]); sort(arr,n);
printf("sorted array is\n");
for(i=0;i<n;i++) printf("%s\
n",arr[i]); return(0);
}
int mycomp(void *a, void *b)
{
return strcmp(*(char **)a,*( char **)b); // type casting to char
}
void sort( char *arr[],int n)
{
qsort(arr,n,sizeof( char *),mycomp); // using QuickSort algorithm to sort the given array.
}

TYPES OF POINTERS:
NULL pointer:

 A NULLpointeris aspecial pointerthat doesnotpoint anywhere.


 It doesnot hold anyaddress.
 It has a numeric value 0.
Declaring NULL pointer:
Syntax Example

datatype* variable_name=0; (Or) int* a=0; (Or)


datatype* variable_name=NULL; int* a=NULL;
#define NULL 0

Points to remember about null pointer:

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.

27
28
3. Dereferencing null pointer leadsto error.

Program to print NULL value: Output:


#include <stdio.h> Value of ptr is 0
int main()
{
// Null Pointer
int *ptr = NULL;

printf("The value of ptr is %u", ptr);


return 0;
}

Void pointer:

 Voidpointerisa general purposepointer that can point to anydata type


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

Declaring void pointer:


Syntax Example

void* variable_name; void* a;

Note: Typecasting is required to change void pointer to specific data type.


1. void pointers cannot be dereferenced. It can however be done using typecasting the void pointer
2. Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
Program using void pointer:
#include<stdlib.h> Output:
int main() Integer variable is = 4
{ Float variable is= 5.500000
int x = 4;
float y = 5.5;
void *ptr;
ptr = &x;
printf("Integer variable is = %d", *((int*) ptr));
ptr = &y;
printf("\nFloat variable is= %f", *((float*) ptr));
return 0;
}
Note:
(int*)ptr - does type casting of void
*((int*)ptr) dereferences(accessing the value) of the typecasted variable

NULL vs Void Pointer – Null pointer is a value, while void pointer is a type

Pointer – Pointer(Double/Chained Pointer):

- Declaring Pointer to Pointer is similar to declaring pointer in C.


- The difference is we have to place an additional ‘*’ before the name of pointer.
- When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that
contains the actual value as shown below.

Declaration:
int **ptr; // declaring double pointers

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

Program for pointer - pointer Output:


int main() Value of var
{ 78
int a= 78; Value of var using single
int *ptr2; // pointer for variable a pointer 78
int **ptr1; // double pointer for ptr2 Value of var using double 78
ptr2 = &a; // storing address of a in ptr2
ptr1 = &ptr2; // Storing address of ptr2 in ptr1
printf("Value of var = %d\n", a );
printf("Value of var using single pointer = %d\n", *ptr2 );
printf("Value of var using double pointer = %d\n", **ptr1);
return 0;
}

POINTERS AND FUNCTIONS:

PARAMETER PASSING METHODS:


There are two ways to pass value or data to function in C language:
i) call by value and
ii) call by reference.
Original value is not modified in call by value but it is modified in call by reference.

Call by Value:

- In call by value, original value is not modified.


- In call by value, value being passed to the function is locally stored by the function parameter.
- So, If you change the value of function parameter, it is changed for the current function only. It will not change the value of
variable inside main().

Passing the value (Call by Value): Output:


#include<stdio.h> Before function call x=10
void my_change(int num); changed value is x=15
int main() After function call x=10
{
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;

30
printf("changed value is x=%d \n",num);
}

Call by Reference(Pass by reference):

 In call by reference, original value is modified because we pass reference (address).


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

Passing the address( Call by Reference): Output:


#include<stdio.h> Before function call x=10
void my_change(int *num); changed value is x=20
int main() After function call x=20
{
int a=10; Note: Value is modified in main
printf("Before function call x=%d \n", a); function.
my_change(&a); //passing value in
function printf("After function call x=%d \n",a);
return(0);
}
void my_change(int *num)
{
*num=*num+10;
printf("changed value is x=%d \n",*num);
}

Difference between call by value and call by reference:


Call by value Call by reference
A copy of value is passed to the function An address of value is passed to the function
Changes made inside the function is not reflected on other Changes made inside the function is reflected outside the function.
functions

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:

31
#include<stdio.h> void swap(int, int); int main()
{
int a=5,b=10;
printf("Before Swap values of a and b is %d %d\n", a, b); swap(a, b);
return(0);
}

void swap(int x, int y)


{
int temp; temp = x; x = y;
y = temp;
printf("after Swap values of a and b is %d %d\n", x, y);
}
Output:
before swap,value of an and b is 5 10 after swap,value of a and b is 10 5

32
#include<stdio.h>
void swap(int *x, int*y); int main()
{
int a=5,b=10;
printf("Before Swap values of a and b is %d %d\n", a, b); swap(&a, &b);
printf("After Swap values of a and b is %d %d\n", a, b); return(0);
}

void swap(int *x, int *y)


{
int temp; temp = *x;
*x = *y;
*y = temp; return;
}

Output:
Before Swap values of a and b is 5 10 After Swap values of a and b is 10 5

33

You might also like