SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Pointers and Dynamic
Memory Allocations
1Presented by: Group-E (The Anonymous)
Bikash Dhakal
Bimal Pradhan
Gagan Puri
Bikram Bhurtel
Rabin BK
Introduction to pointers
Declaration of pointer
Accessing a variable through pointer
Chain of pointers
Pointer expression
Pointers and Array
Pointer to function
Pointer to structure
Trouble with pointers
Memory allocation
Dynamic Memory Allocation
Refrences
2
3
Computer use their memory for storing instructions of the
programs.
Pointers are more efficient in handling arrays and data types
It allows C to support dynamic memory management
It reduces length and complexity of programs
Pointer Declaration
4
Pointer is a variable which can hold the address of a
memory location
The value stored in a pointer type variable is interpreted
as an address
Pointer
It contain address that belongs to separate data type
It can be declared just like any other variables
It takes the following form:
data_type *pointer_name;
The above statement tells the compiler three things above the
variables pointer_name
5
Pointer Declaration
1. The asterisk(*) tells that the variables pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.
Example:
Pointer declaration Interpretation
Int *rollnumber; Create a pointer variables rollnumber capable of pointing to an integer type
variable or capable of holding the address of an integer type variable
Char *name; Create a pointer variable name capable of pointing to a character type variable
or capable of holding the address of a character type
Float *salary; Create a pointer variable salary capable of pointing to a float type variable or
capable of holding the address of a float type variable
6
The process of assigning the address of a variables to a pointer variable
called initialization
As pointer out earlier, all uninitialized pointers will have same unknown
values that will be interpreted as memory address
It takes the following form:
datatype*pointer_name = & ordinary_variabl e_name
7
Initialization of Pointer variables
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int x, *p;
printf("Enter a number: ");
scanf("%d",&x);
p = &x;
printf("n value of x=%d",*p);
printf("n Address of x using pointer = %u",p);
printf("n Address of x using & pointer = %u",&x);
getch();
}
8
Unary operator also known as indirect operator * (asterick) used to access the
value of variable using pointer.
data_type *p=& ordinary_variable_name
eg :- int quantity ,*p , n
quantity =123;
p=&quantity;
n=*p;
#include<stdio.h>
#include<conio.h>
void main()
{
int x, *p;
printf("Enter a number: ");
scanf("%d",&x);
p = &x;
printf("n value of x=%d",*p);
printf("n Address of x using pointer = %u",p);
printf("n Address of x using & pointer = %u",&x);
getch();
}
9
Accessing a variable through its pointer
 Chain of pointer can be created by pointing a pointer to another pointer.
P₂ P₁ variable
 Here pointer variable P₂ contains the address of the pointer variable P₁ , which
points to the location that contains the desire value .
 also known as multiple indirections operators.
Address 2 Address 1 value
10
Chain of pointers
void main()
{
int x,*p1,**p2;
x=100;
p1=&x;
p2=p1;
printf(“%d”,**p2);
}
11
 Pointer variables can be used in expression.
 C allows us to add integers to or subtract integers from pointer , as well as allows
to subtract one from another.
like , p1+p2 , p1-p2 etc
 Two pointers can also be compared using the relational operators .
like , p1>p2 , p1==p2 etc
 However pointer cannot be use in multiple or division and also cannot be added.
12
Pointer expression
Syntax:
data_type *pointer_name[size]
Example:-
void main()
{
int *p[3]
int a=2, b=3, c=4;
p[0]=&a;
p[1]=&b;
p[2]=&c;
for(i=0;i<3;i++)
{
printf (“value =%d”,*p[i])
}
} 13
Pointers and Array
→ ARRAY OF POINTER
 Array name itself is a pointer that points to it’s zeroth element
Example:-
int a[5]
the array name a → &a[0]
 When the pointer a is incremented by 1
it gives address of oneth element and so on
i.e. a+1→ &a[1]
a+2→ &a[2]
a+i→ &a[i]
Thus *(a+i)→ a[i]
Example :-
void main()
{
int a[2],i;
printf(“input array
elements:”);
for (i=0;i<5;i++)
{
scanf(“%d”,a+1);
}
printf(”n array elements
are:”);
for (i=0;i<5;i++)
{
printf(“%dt”,*(a+i));
}
}
Relation between Array and Pointers
14
Pointer and string
Strings are character arrays
for string syntax
char str[6]=”hello” → null character at the end of string
but in pointer to string
char *str = ”hello”
char *cards[ 4 ] = {"Hearts", "Diamonds",
"Clubs",”spades” }; → here it represents
that the strings are not in the array, only pointers to the strings are in the array
15
 Call by reference method is used
 The address of data items is passed to the function
 Data items can be altered globally from within the function
Pointer to a Function
16
Example:
#include<stdio.h>
void swap (int*p, int*q);
int main()
{
int x,y;
x=50;
y=70;
printf("nValue of x and y before swap are :
%dt%d",x,y);
swap(&x,&y);
printf ("Values of x and y after swap are:
%dt%d",x,y);
return 0;
}
void swap(int*p, int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
Values of x and y before swap are : 50 70
Values of x and y after swap are : 70 50
17
 pointers pointing to a struct are known as "Structure Pointers"
 address of a structure variable is assigned to the pointer
variable
 pointer variables which stores address of structure must be
declared as pointer to structure
18
Pointer to structure
#include <stdio.h>
#include <conio.h>
struct employee
{
char name [20];
int id;
float salary;
};
void main()
{
struct employee e1 ={"John",201,10000.50};
struct employee *e;
e=&e1;
printf("n%st%dt%.2f",e->name,e->id,e->salary);
getch();
} 19
20
Trouble with Pointers
 Compiler may not detect the error and produce unnecessary
results
 Debugging becomes difficult
 Some common errors
int *p, m=100;
p=m;
p=&m;
printf(“%d”,p);
21
Types of memory allocation
Fixed in size
Automatic memory allocation
space is automatically determined
E.g: int a =10; (2 bytes space is occupied in memory)
Static Memory Allocation (SMA)
Fixed in size
Done at compile time only
Cannot take data more than the allocated size
E.g: char mem_alloc[12];
int a[5]={1,6,9,4,11};
Often real world problems meaning that, required storage space
changes over time
Size can be changed
Done at run time
We can allocate (create) and deallocate (free/delete) storage space
whenever needed
We can always have exact amount of storage space (no more, no less)
There are 4 library functions that come into action for the DMA:
malloc()
calloc()
realloc()
free() 22
Dynamic Memory Allocation (DMA)
Syntax:
m=(cast-type*)malloc(size-in-bytes)
Reserves a (single) block of memory of specified size in bytes
Returns a pointer of void type to the first byte of the space which is
allocated
23
malloc()
E.g:
a=(int*)malloc(10*sizeof(int));
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *a,i;
float num;
printf("Enter size for memory allocation: ");
scanf("%f",&num);
a=(int*)malloc(sizeof(num));
printf("Allocated memory is: ");
for(i = 0; i < num; ++i)
{
printf("%ut",a+i);
}
free(a);
getch();
} 24
calloc()
Syntax:
m=(cast-type*)calloc(n,element-size)
Reserves multiple block of memory each of same size and sets all
bytes to zero
The difference in malloc and calloc is that malloc does not set the
memory to zero where as calloc sets allocated memory to zero.
25
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *a,i;
float num;
printf("Enter size for memory allocation: ");
scanf("%f",&num);
a=(int*)calloc(num,sizeof(int));
printf("Allocated memory is: ");
for(i = 0; i < num; ++i)
{
printf("%ut",a+i);
}
free(a);
getch();
} 26
realloc()
Syntax:
m= (int*) malloc(size from the user);
-------------------
m=(cast-type*)realloc(n, new-size)
Used to increase or decrease the allocated memory size using malloc()
or calloc() functions
It adjusts the old memory region if the new size is smaller than the
size of old memory
If the new size is larger than the existing memory size, it increases the
size by copying the contents of old memory region to new memory
region
27
#include <stdlib.h>
void main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
{
printf("%ut",ptr + i);
}
printf("nEnter new size of array: ");
scanf("%d", &n2);
ptr = (int*) realloc(ptr, n2);
for(i = 0; i < n2; ++i)
{
printf("%ut", ptr + i);
}
getch();
}
28
References:
Websites:
google.com
codecadamy.com
tutorialspoint.com
External sources:
Text book: Programming in ANSIC (E-Balagurusamy)
29
Queries
30

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
Python strings
Python stringsPython strings
Python strings
 
Python recursion
Python recursionPython recursion
Python recursion
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 

Ähnlich wie Pointers and Dynamic Memory Allocation

Ähnlich wie Pointers and Dynamic Memory Allocation (20)

Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
 
Input output functions
Input output functionsInput output functions
Input output functions
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
See through C
See through CSee through C
See through C
 
presentation_pointers_1444076066_140676 (1).ppt
presentation_pointers_1444076066_140676 (1).pptpresentation_pointers_1444076066_140676 (1).ppt
presentation_pointers_1444076066_140676 (1).ppt
 
c program.ppt
c program.pptc program.ppt
c program.ppt
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
Chapter09-10.PPT
Chapter09-10.PPTChapter09-10.PPT
Chapter09-10.PPT
 
Chapter09-10 Pointers and operations .PPT
Chapter09-10  Pointers and operations .PPTChapter09-10  Pointers and operations .PPT
Chapter09-10 Pointers and operations .PPT
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
Pointer
PointerPointer
Pointer
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 

Mehr von Rabin BK

Artificial Intelligence in E-commerce
Artificial Intelligence in E-commerceArtificial Intelligence in E-commerce
Artificial Intelligence in E-commerceRabin BK
 
Three address code generation
Three address code generationThree address code generation
Three address code generationRabin BK
 
Consumer Oriented Application, Mercantile process and Mercantile models
Consumer Oriented Application, Mercantile process and Mercantile modelsConsumer Oriented Application, Mercantile process and Mercantile models
Consumer Oriented Application, Mercantile process and Mercantile modelsRabin BK
 
Clang compiler `
Clang compiler `Clang compiler `
Clang compiler `Rabin BK
 
Simple Mail Transfer Protocol
Simple Mail Transfer ProtocolSimple Mail Transfer Protocol
Simple Mail Transfer ProtocolRabin BK
 
HTML text formatting tags
HTML text formatting tagsHTML text formatting tags
HTML text formatting tagsRabin BK
 
Data encryption in database management system
Data encryption in database management systemData encryption in database management system
Data encryption in database management systemRabin BK
 
Object Relational Database Management System(ORDBMS)
Object Relational Database Management System(ORDBMS)Object Relational Database Management System(ORDBMS)
Object Relational Database Management System(ORDBMS)Rabin BK
 
Kolmogorov Smirnov
Kolmogorov SmirnovKolmogorov Smirnov
Kolmogorov SmirnovRabin BK
 
Job sequencing in Data Strcture
Job sequencing in Data StrctureJob sequencing in Data Strcture
Job sequencing in Data StrctureRabin BK
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data StructureRabin BK
 
Data Science
Data ScienceData Science
Data ScienceRabin BK
 
Graphics_3D viewing
Graphics_3D viewingGraphics_3D viewing
Graphics_3D viewingRabin BK
 
Neural Netwrok
Neural NetwrokNeural Netwrok
Neural NetwrokRabin BK
 
Watermarking in digital images
Watermarking in digital imagesWatermarking in digital images
Watermarking in digital imagesRabin BK
 
Heun's Method
Heun's MethodHeun's Method
Heun's MethodRabin BK
 
Mutual Exclusion
Mutual ExclusionMutual Exclusion
Mutual ExclusionRabin BK
 
Systems Usage
Systems UsageSystems Usage
Systems UsageRabin BK
 
Manager of a company
Manager of a companyManager of a company
Manager of a companyRabin BK
 

Mehr von Rabin BK (20)

Artificial Intelligence in E-commerce
Artificial Intelligence in E-commerceArtificial Intelligence in E-commerce
Artificial Intelligence in E-commerce
 
Three address code generation
Three address code generationThree address code generation
Three address code generation
 
Consumer Oriented Application, Mercantile process and Mercantile models
Consumer Oriented Application, Mercantile process and Mercantile modelsConsumer Oriented Application, Mercantile process and Mercantile models
Consumer Oriented Application, Mercantile process and Mercantile models
 
Clang compiler `
Clang compiler `Clang compiler `
Clang compiler `
 
Simple Mail Transfer Protocol
Simple Mail Transfer ProtocolSimple Mail Transfer Protocol
Simple Mail Transfer Protocol
 
HTML text formatting tags
HTML text formatting tagsHTML text formatting tags
HTML text formatting tags
 
Data encryption in database management system
Data encryption in database management systemData encryption in database management system
Data encryption in database management system
 
Object Relational Database Management System(ORDBMS)
Object Relational Database Management System(ORDBMS)Object Relational Database Management System(ORDBMS)
Object Relational Database Management System(ORDBMS)
 
Kolmogorov Smirnov
Kolmogorov SmirnovKolmogorov Smirnov
Kolmogorov Smirnov
 
Job sequencing in Data Strcture
Job sequencing in Data StrctureJob sequencing in Data Strcture
Job sequencing in Data Strcture
 
Stack Data Structure
Stack Data StructureStack Data Structure
Stack Data Structure
 
Bluetooth
BluetoothBluetooth
Bluetooth
 
Data Science
Data ScienceData Science
Data Science
 
Graphics_3D viewing
Graphics_3D viewingGraphics_3D viewing
Graphics_3D viewing
 
Neural Netwrok
Neural NetwrokNeural Netwrok
Neural Netwrok
 
Watermarking in digital images
Watermarking in digital imagesWatermarking in digital images
Watermarking in digital images
 
Heun's Method
Heun's MethodHeun's Method
Heun's Method
 
Mutual Exclusion
Mutual ExclusionMutual Exclusion
Mutual Exclusion
 
Systems Usage
Systems UsageSystems Usage
Systems Usage
 
Manager of a company
Manager of a companyManager of a company
Manager of a company
 

Kürzlich hochgeladen

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Kürzlich hochgeladen (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Pointers and Dynamic Memory Allocation

  • 1. Pointers and Dynamic Memory Allocations 1Presented by: Group-E (The Anonymous) Bikash Dhakal Bimal Pradhan Gagan Puri Bikram Bhurtel Rabin BK
  • 2. Introduction to pointers Declaration of pointer Accessing a variable through pointer Chain of pointers Pointer expression Pointers and Array Pointer to function Pointer to structure Trouble with pointers Memory allocation Dynamic Memory Allocation Refrences 2
  • 3. 3 Computer use their memory for storing instructions of the programs. Pointers are more efficient in handling arrays and data types It allows C to support dynamic memory management It reduces length and complexity of programs Pointer Declaration
  • 4. 4 Pointer is a variable which can hold the address of a memory location The value stored in a pointer type variable is interpreted as an address Pointer
  • 5. It contain address that belongs to separate data type It can be declared just like any other variables It takes the following form: data_type *pointer_name; The above statement tells the compiler three things above the variables pointer_name 5 Pointer Declaration
  • 6. 1. The asterisk(*) tells that the variables pt_name is a pointer variable. 2. pt_name needs a memory location. 3. pt_name points to a variable of type data type. Example: Pointer declaration Interpretation Int *rollnumber; Create a pointer variables rollnumber capable of pointing to an integer type variable or capable of holding the address of an integer type variable Char *name; Create a pointer variable name capable of pointing to a character type variable or capable of holding the address of a character type Float *salary; Create a pointer variable salary capable of pointing to a float type variable or capable of holding the address of a float type variable 6
  • 7. The process of assigning the address of a variables to a pointer variable called initialization As pointer out earlier, all uninitialized pointers will have same unknown values that will be interpreted as memory address It takes the following form: datatype*pointer_name = & ordinary_variabl e_name 7 Initialization of Pointer variables
  • 8. Example: #include<stdio.h> #include<conio.h> void main() { int x, *p; printf("Enter a number: "); scanf("%d",&x); p = &x; printf("n value of x=%d",*p); printf("n Address of x using pointer = %u",p); printf("n Address of x using & pointer = %u",&x); getch(); } 8
  • 9. Unary operator also known as indirect operator * (asterick) used to access the value of variable using pointer. data_type *p=& ordinary_variable_name eg :- int quantity ,*p , n quantity =123; p=&quantity; n=*p; #include<stdio.h> #include<conio.h> void main() { int x, *p; printf("Enter a number: "); scanf("%d",&x); p = &x; printf("n value of x=%d",*p); printf("n Address of x using pointer = %u",p); printf("n Address of x using & pointer = %u",&x); getch(); } 9 Accessing a variable through its pointer
  • 10.  Chain of pointer can be created by pointing a pointer to another pointer. P₂ P₁ variable  Here pointer variable P₂ contains the address of the pointer variable P₁ , which points to the location that contains the desire value .  also known as multiple indirections operators. Address 2 Address 1 value 10 Chain of pointers
  • 12.  Pointer variables can be used in expression.  C allows us to add integers to or subtract integers from pointer , as well as allows to subtract one from another. like , p1+p2 , p1-p2 etc  Two pointers can also be compared using the relational operators . like , p1>p2 , p1==p2 etc  However pointer cannot be use in multiple or division and also cannot be added. 12 Pointer expression
  • 13. Syntax: data_type *pointer_name[size] Example:- void main() { int *p[3] int a=2, b=3, c=4; p[0]=&a; p[1]=&b; p[2]=&c; for(i=0;i<3;i++) { printf (“value =%d”,*p[i]) } } 13 Pointers and Array → ARRAY OF POINTER
  • 14.  Array name itself is a pointer that points to it’s zeroth element Example:- int a[5] the array name a → &a[0]  When the pointer a is incremented by 1 it gives address of oneth element and so on i.e. a+1→ &a[1] a+2→ &a[2] a+i→ &a[i] Thus *(a+i)→ a[i] Example :- void main() { int a[2],i; printf(“input array elements:”); for (i=0;i<5;i++) { scanf(“%d”,a+1); } printf(”n array elements are:”); for (i=0;i<5;i++) { printf(“%dt”,*(a+i)); } } Relation between Array and Pointers 14
  • 15. Pointer and string Strings are character arrays for string syntax char str[6]=”hello” → null character at the end of string but in pointer to string char *str = ”hello” char *cards[ 4 ] = {"Hearts", "Diamonds", "Clubs",”spades” }; → here it represents that the strings are not in the array, only pointers to the strings are in the array 15
  • 16.  Call by reference method is used  The address of data items is passed to the function  Data items can be altered globally from within the function Pointer to a Function 16
  • 17. Example: #include<stdio.h> void swap (int*p, int*q); int main() { int x,y; x=50; y=70; printf("nValue of x and y before swap are : %dt%d",x,y); swap(&x,&y); printf ("Values of x and y after swap are: %dt%d",x,y); return 0; } void swap(int*p, int*q) { int temp; temp=*p; *p=*q; *q=temp; } Values of x and y before swap are : 50 70 Values of x and y after swap are : 70 50 17
  • 18.  pointers pointing to a struct are known as "Structure Pointers"  address of a structure variable is assigned to the pointer variable  pointer variables which stores address of structure must be declared as pointer to structure 18 Pointer to structure
  • 19. #include <stdio.h> #include <conio.h> struct employee { char name [20]; int id; float salary; }; void main() { struct employee e1 ={"John",201,10000.50}; struct employee *e; e=&e1; printf("n%st%dt%.2f",e->name,e->id,e->salary); getch(); } 19
  • 20. 20 Trouble with Pointers  Compiler may not detect the error and produce unnecessary results  Debugging becomes difficult  Some common errors int *p, m=100; p=m; p=&m; printf(“%d”,p);
  • 21. 21 Types of memory allocation Fixed in size Automatic memory allocation space is automatically determined E.g: int a =10; (2 bytes space is occupied in memory) Static Memory Allocation (SMA) Fixed in size Done at compile time only Cannot take data more than the allocated size E.g: char mem_alloc[12]; int a[5]={1,6,9,4,11};
  • 22. Often real world problems meaning that, required storage space changes over time Size can be changed Done at run time We can allocate (create) and deallocate (free/delete) storage space whenever needed We can always have exact amount of storage space (no more, no less) There are 4 library functions that come into action for the DMA: malloc() calloc() realloc() free() 22 Dynamic Memory Allocation (DMA)
  • 23. Syntax: m=(cast-type*)malloc(size-in-bytes) Reserves a (single) block of memory of specified size in bytes Returns a pointer of void type to the first byte of the space which is allocated 23 malloc() E.g: a=(int*)malloc(10*sizeof(int));
  • 24. #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int *a,i; float num; printf("Enter size for memory allocation: "); scanf("%f",&num); a=(int*)malloc(sizeof(num)); printf("Allocated memory is: "); for(i = 0; i < num; ++i) { printf("%ut",a+i); } free(a); getch(); } 24
  • 25. calloc() Syntax: m=(cast-type*)calloc(n,element-size) Reserves multiple block of memory each of same size and sets all bytes to zero The difference in malloc and calloc is that malloc does not set the memory to zero where as calloc sets allocated memory to zero. 25
  • 26. #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int *a,i; float num; printf("Enter size for memory allocation: "); scanf("%f",&num); a=(int*)calloc(num,sizeof(int)); printf("Allocated memory is: "); for(i = 0; i < num; ++i) { printf("%ut",a+i); } free(a); getch(); } 26
  • 27. realloc() Syntax: m= (int*) malloc(size from the user); ------------------- m=(cast-type*)realloc(n, new-size) Used to increase or decrease the allocated memory size using malloc() or calloc() functions It adjusts the old memory region if the new size is smaller than the size of old memory If the new size is larger than the existing memory size, it increases the size by copying the contents of old memory region to new memory region 27
  • 28. #include <stdlib.h> void main() { int *ptr, i , n1, n2; printf("Enter size of array: "); scanf("%d", &n1); ptr = (int*) malloc(n1*sizeof(int)); printf("Address of previously allocated memory: "); for(i = 0; i < n1; ++i) { printf("%ut",ptr + i); } printf("nEnter new size of array: "); scanf("%d", &n2); ptr = (int*) realloc(ptr, n2); for(i = 0; i < n2; ++i) { printf("%ut", ptr + i); } getch(); } 28