SlideShare a Scribd company logo
October 29, 2024 Programming and Data Structure 1
Pointers
October 29, 2024 Programming and Data Structure 2
Introduction
• A pointer is a variable that represents the
location (rather than the value) of a data item.
• They have a number of useful applications.
– Enables us to access a variable that is defined
outside the function.
– Can be used to pass information back and forth
between a function and its reference point.
– More efficient in handling data tables.
– Reduces the length and complexity of a program.
– Sometimes also increases the execution speed.
October 29, 2024 Programming and Data Structure 3
Basic Concept
• Within the computer memory, every stored data
item occupies one or more contiguous memory
cells.
– The number of memory cells required to store a data
item depends on its type (char, int, double, etc.).
• Whenever we declare a variable, the system
allocates memory location(s) to hold the value of
the variable.
– Since every byte in memory has a unique address, this
location will also have its own (unique) address.
October 29, 2024 Programming and Data Structure 4
Contd.
• Consider the statement
int xyz = 50;
– This statement instructs the compiler to allocate a
location for the integer variable xyz, and put the
value 50 in that location.
– Suppose that the address location chosen is 1380.
xyz  variable
50  value
1380  address
October 29, 2024 Programming and Data Structure 5
Contd.
• During execution of the program, the system
always associates the name xyz with the
address 1380.
– The value 50 can be accessed by using either the
name xyz or the address 1380.
• Since memory addresses are simply numbers,
they can be assigned to some variables which
can be stored in memory.
– Such variables that hold memory addresses are
called pointers.
– Since a pointer is a variable, its value is also stored
in some memory location.
October 29, 2024 Programming and Data Structure 6
Contd.
• Suppose we assign the address of xyz to a
variable p.
– p is said to point to the variable xyz.
Variable Value Address
xyz 50 1380
p 1380 2545
p = &xyz;
50
1380
xyz
1380
2545
p
October 29, 2024 Programming and Data Structure 7
Accessing the Address of a Variable
• The address of a variable can be determined
using the ‘&’ operator.
– The operator ‘&’ immediately preceding a variable
returns the address of the variable.
• Example:
p = &xyz;
– The address of xyz (1380) is assigned to p.
• The ‘&’ operator can be used only with a
simple variable or an array element.
&distance
&x[0]
&x[i-2]
October 29, 2024 Programming and Data Structure 8
Contd.
• Following usages are illegal:
&235
• Pointing at constant.
int arr[20];
:
&arr;
• Pointing at array name.
&(a+b)
• Pointing at expression.
October 29, 2024 Programming and Data Structure 9
Example
#include <stdio.h>
main()
{
int a;
float b, c;
double d;
char ch;
a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = ‘A’;
printf (“%d is stored in location %u n”, a, &a) ;
printf (“%f is stored in location %u n”, b, &b) ;
printf (“%f is stored in location %u n”, c, &c) ;
printf (“%ld is stored in location %u n”, d, &d) ;
printf (“%c is stored in location %u n”, ch, &ch) ;
}
October 29, 2024 Programming and Data Structure 10
Output:
10 is stored in location 3221224908
2.500000 is stored in location 3221224904
12.360000 is stored in location 3221224900
12345.660000 is stored in location 3221224892
A is stored in location 3221224891
Incidentally variables a,b,c,d and ch are allocated
to contiguous memory locations.
a
b
c
d
ch
October 29, 2024 Programming and Data Structure 11
Pointer Declarations
• Pointer variables must be declared before we
use them.
• General form:
data_type *pointer_name;
Three things are specified in the above
declaration:
1. The asterisk (*) tells that the variable pointer_name is a
pointer variable.
2. pointer_name needs a memory location.
3. pointer_name points to a variable of type data_type.
October 29, 2024 Programming and Data Structure 12
Contd.
• Example:
int *count;
float *speed;
• Once a pointer variable has been declared, it
can be made to point to a variable using an
assignment statement like:
int *p, xyz;
:
p = &xyz;
– This is called pointer initialization.
October 29, 2024 Programming and Data Structure 13
Things to Remember
• Pointer variables must always point to a data
item of the same type.
float x;
int *p;
:  will result in erroneous output
p = &x;
• Assigning an absolute address to a pointer
variable is prohibited.
int *count;
:
count = 1268;
October 29, 2024 Programming and Data Structure 14
Accessing a Variable Through its Pointer
• Once a pointer has been assigned the address of
a variable, the value of the variable can be
accessed using the indirection operator (*).
int a, b;
int *p;
:
p = &a;
b = *p;
Equivalent to b = a
October 29, 2024 Programming and Data Structure 15
Example 1
#include <stdio.h>
main()
{
int a, b;
int c = 5;
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d n”, a, b) ;
}
Equivalent
October 29, 2024 Programming and Data Structure 16
Example 2
#include <stdio.h>
main()
{
int x, y;
int *ptr;
x = 10 ;
ptr = &x ;
y = *ptr ;
printf (“%d is stored in location %u n”, x, &x) ;
printf (“%d is stored in location %u n”, *&x, &x) ;
printf (“%d is stored in location %u n”, *ptr, ptr) ;
printf (“%d is stored in location %u n”, y, &*ptr) ;
printf (“%u is stored in location %u n”, ptr, &ptr) ;
printf (“%d is stored in location %u n”, y, &y) ;
*ptr = 25;
printf (“nNow x = %d n”, x);
}
*&xx
ptr=&x;
&x&*ptr
October 29, 2024 Programming and Data Structure 17
Output:
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
3221224908 is stored in location 3221224900
10 is stored in location 3221224904
Now x = 25
Address of x: 3221224908
Address of y: 3221224904
Address of ptr: 3221224900
October 29, 2024 Programming and Data Structure 18
Pointer Expressions
• Like other variables, pointer variables can be
used in expressions.
• If p1 and p2 are two pointers, the following
statements are valid:
sum = *p1 + *p2 ;
prod = *p1 * *p2 ;
prod = (*p1) * (*p2) ;
*p1 = *p1 + 2;
x = *p1 / *p2 + 5 ;
October 29, 2024 Programming and Data Structure 19
Contd.
• What are allowed in C?
– Add an integer to a pointer.
– Subtract an integer from a pointer.
– Subtract one pointer from another (related).
• If p1 and p2 are both pointers to the same array, them
p2–p1 gives the number of elements between p1 and p2.
• What are not allowed?
– Add two pointers.
p1 = p1 + p2 ;
– Multiply / divide a pointer in an expression.
p1 = p2 / 5 ;
p1 = p1 – p2 * 10 ;
October 29, 2024 Programming and Data Structure 20
Scale Factor
• We have seen that an integer value can be
added to or subtracted from a pointer variable.
int *p1, *p2 ;
int i, j;
:
p1 = p1 + 1 ;
p2 = p1 + j ;
p2++ ;
p2 = p2 – (i + j) ;
• In reality, it is not the integer value which is
added/subtracted, but rather the scale factor
times the value.
October 29, 2024 Programming and Data Structure 21
Contd.
Data Type Scale Factor
char 1
int 4
float 4
double 8
– If p1 is an integer pointer, then
p1++
will increment the value of p1 by 4.
October 29, 2024 Programming and Data Structure 22
Example: to find the scale factors
#include <stdio.h>
main()
{
printf (“Number of bytes occupied by int is %d n”, sizeof(int));
printf (“Number of bytes occupied by float is %d n”, sizeof(float));
printf (“Number of bytes occupied by double is %d n”, sizeof(double));
printf (“Number of bytes occupied by char is %d n”, sizeof(char));
}
Output:
Number of bytes occupied by int is 4
Number of bytes occupied by float is 4
Number of bytes occupied by double is 8
Number of bytes occupied by char is 1
Returns no. of bytes required for data type representation
October 29, 2024 Programming and Data Structure 23
Example: Sort 3 integers
• Three-step algorithm:
1. Read in three integers x, y and z
2. Put smallest in x
• Swap x, y if necessary; then swap x, z if necessary.
3. Put second smallest in y
• Swap y, z if necessary.
October 29, 2024 Programming and Data Structure 24
Contd.
#include <stdio.h>
main()
{
int x, y, z ;
………..
scanf (“%d %d %d”, &x, &y, &z) ;
if (x > y) swap (&x, &y);
if (x > z) swap (&x, &z);
if (y > z) swap (&y, &z) ;
………..
}
October 29, 2024 Programming and Data Structure 25
Dynamic Memory Allocation
October 29, 2024 Programming and Data Structure 26
Basic Idea
• Many a time we face situations where data is
dynamic in nature.
– Amount of data cannot be predicted beforehand.
– Number of data item keeps changing during
program execution.
• Such situations can be handled more easily and
effectively using dynamic memory management
techniques.
October 29, 2024 Programming and Data Structure 27
Contd.
• C language requires the number of elements in
an array to be specified at compile time.
– Often leads to wastage or memory space or program
failure.
• Dynamic Memory Allocation
– Memory space required can be specified at the time
of execution.
– C supports allocating and freeing memory
dynamically using library routines.
October 29, 2024 Programming and Data Structure 28
Memory Allocation Process in C
Local variables
Free memory
Global variables
Instructions
Permanent storage
area
Stack
Heap
October 29, 2024 Programming and Data Structure 29
Contd.
• The program instructions and the global
variables are stored in a region known as
permanent storage area.
• The local variables are stored in another area
called stack.
• The memory space between these two areas is
available for dynamic allocation during
execution of the program.
– This free region is called the heap.
– The size of the heap keeps changing
October 29, 2024 Programming and Data Structure 30
Memory Allocation Functions
• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space.
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
• free
Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
October 29, 2024 Programming and Data Structure 31
Allocating a Block of Memory
• A block of memory can be allocated using the
function malloc.
– Reserves a block of memory of specified size and
returns a pointer of type void.
– The return pointer can be assigned to any pointer
type.
• General format:
ptr = (type *) malloc (byte_size) ;
October 29, 2024 Programming and Data Structure 32
Contd.
• Examples
p = (int *) malloc (100 * sizeof (int)) ;
• A memory space equivalent to “100 times the size of an
int” bytes is reserved.
• The address of the first byte of the allocated memory is
assigned to the pointer p of type int.
p
400 bytes of space
October 29, 2024 Programming and Data Structure 33
Contd.
cptr = (char *) malloc (20) ;
• Allocates 10 bytes of space for the pointer cptr of type char.
sptr = (struct stud *) malloc (10 *
sizeof (struct stud));
October 29, 2024 Programming and Data Structure 34
Points to Note
• malloc always allocates a block of contiguous
bytes.
– The allocation can fail if sufficient contiguous
memory space is not available.
– If it fails, malloc returns NULL.
October 29, 2024 Programming and Data Structure 35
Example
printf("Input heights for %d
students n",N);
for(i=0;i<N;i++)
scanf("%f",&height[i]);
for(i=0;i<N;i++)
sum+=height[i];
avg=sum/(float) N;
printf("Average height= %f n",
avg);
}
#include <stdio.h>
main()
{
int i,N;
float *height;
float sum=0,avg;
printf("Input the number of students. n");
scanf("%d",&N);
height=(float *) malloc(N * sizeof(float));
Input the number of students.
5
Input heights for 5 students
23 24 25 26 27
Average height= 25.000000
October 29, 2024 Programming and Data Structure 36
Releasing the Used Space
• When we no longer need the data stored in a
block of memory, we may release the block for
future use.
• How?
– By using the free function.
• General format:
free (ptr) ;
where ptr is a pointer to a memory block which
has been already created using malloc.
October 29, 2024 Programming and Data Structure 37
Altering the Size of a Block
• Sometimes we need to alter the size of some
previously allocated memory block.
– More memory needed.
– Memory allocated is larger than necessary.
• How?
– By using the realloc function.
• If the original allocation is done by the statement
ptr = malloc (size) ;
then reallocation of space may be done as
ptr = realloc (ptr, newsize) ;
October 29, 2024 Programming and Data Structure 38
Contd.
– The new memory block may or may not begin at the
same place as the old one.
• If it does not find space, it will create it in an entirely
different region and move the contents of the old block into
the new block.
– The function guarantees that the old data remains
intact.
– If it is unable to allocate, it returns NULL and frees
the original block.
October 29, 2024 Programming and Data Structure 39
Pointer to Pointer
• Example:
int **p;
p=(int **) malloc(3 * sizeof(int *));
p
p[2]
p[1]
p[0]
int *
int **
int *
int *
October 29, 2024 Programming and Data Structure 40
2-D Array Allocation
#include <stdio.h>
#include <stdlib.h>
int **allocate(int h, int w)
{
int **p;
int i,j;
p=(int **) calloc(h, sizeof (int *) );
for(i=0;i<h;i++)
p[i]=(int *) calloc(w,sizeof (int));
return(p);
}
void read_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
for(j=0;j<w;j++)
scanf ("%d",&p[i][j]);
}
Allocate array
of pointers
Allocate array of
integers for each
row
Elements accessed
like 2-D array elements.
October 29, 2024 Programming and Data Structure 41
void print_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
printf("%5d ",p[i][j]);
printf("n");
}
}
2-D Array: Contd.
main()
{
int **p;
int M,N;
printf("Give M and N n");
scanf("%d%d",&M,&N);
p=allocate(M,N);
read_data(p,M,N);
printf("n The array read as n");
print_data(p,M,N);
}
Give M and N
3 3
1 2 3
4 5 6
7 8 9
The array read as
1 2 3
4 5 6
7 8 9
October 29, 2024 Programming and Data Structure 42
Linked List :: Basic Concepts
• A list refers to a set of items organized
sequentially.
– An array is an example of a list.
• The array index is used for accessing and manipulation of
array elements.
– Problems with array:
• The array size has to be specified at the beginning.
• Deleting an element or inserting an element may require
shifting of elements.
October 29, 2024 Programming and Data Structure 43
Contd.
• A completely different way to represent a list:
– Make each item in the list part of a structure.
– The structure also contains a pointer or link to the
structure containing the next item.
– This type of list is called a linked list.
Structure 1
item
Structure 2
item
Structure 3
item
October 29, 2024 Programming and Data Structure 44
Contd.
• Each structure of the list is called a node, and
consists of two fields:
– One containing the item.
– The other containing the address of the next item in
the list.
• The data items comprising a linked list need
not be contiguous in memory.
– They are ordered by logical links that are stored as
part of the data in the structure itself.
– The link is a pointer to another structure of the
same type.
October 29, 2024 Programming and Data Structure 45
Contd.
• Such a structure can be represented as:
struct node
{
int item;
struct node *next;
} ;
• Such structures which contain a member field
pointing to the same structure type are called
self-referential structures.
item
node
next
October 29, 2024 Programming and Data Structure 46
Contd.
• In general, a node may be represented as
follows:
struct node_name
{
type member1;
type member2;
………
struct node_name *next;
};
October 29, 2024 Programming and Data Structure 47
Illustration
• Consider the structure:
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
• Also assume that the list consists of three nodes
n1, n2 and n3.
struct stud n1, n2, n3;
October 29, 2024 Programming and Data Structure 48
Contd.
• To create the links between nodes, we can
write:
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ; /* No more nodes follow */
• Now the list looks like:
n1 n2 n3
roll
name
age
next
October 29, 2024 Programming and Data Structure 49
Example
#include <stdio.h>
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
main()
{
struct stud n1, n2, n3;
struct stud *p;
scanf (“%d %s %d”, &n1.roll,
n1.name, &n1.age);
scanf (“%d %s %d”, &n2.roll,
n2.name, &n2.age);
scanf (“%d %s %d”, &n3.roll,
n3.name, &n3.age);
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ;
/* Now traverse the list and print
the elements */
p = n1 ; /* point to 1st
element */
while (p != NULL)
{
printf (“n %d %s %d”,
p->roll, p->name, p->age);
p = p->next;
}
}

More Related Content

Similar to l7-pointersthroughmemoryinvarious languages.ppt (20)

PPTX
Address, Pointers, Arrays, and Structures.pptx
Dr. Amna Mohamed
 
PPTX
Data Structure & aaplications_Module-1.pptx
GIRISHKUMARBC1
 
PPT
pointers CP Lecture.ppt
EC42ShaikhAmaan
 
PPT
Session 5
Shailendra Mathur
 
PPTX
CSE 1102 - Lecture_8 - Pointers_in_C.pptx
Salim Shadman Ankur
 
PPTX
Pointers
Munazza-Mah-Jabeen
 
PPT
358 33 powerpoint-slides_3-pointers_chapter-3
sumitbardhan
 
PPTX
Introduction to Data Structure
chouguleamruta24
 
PPTX
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
PPT
Pointers C programming
Appili Vamsi Krishna
 
PPT
Lecture1
Muhammad Zubair
 
PPT
ch08.ppt
NewsMogul
 
PPTX
Data Structure Introduction for Beginners
ramanathan2006
 
PDF
Memory Management for C and C++ _ language
23ecuos117
 
PPTX
C Programming : Pointers and Arrays, Pointers and Strings
Selvaraj Seerangan
 
PPTX
pointers_final.pptxxxxxxxxxxxxxxxxxxxxxx
assignmenthet
 
PPT
Pointers definition syntax structure use
dheeraj658032
 
PPT
Chapter09-10 Pointers and operations .PPT
ShalabhMishra10
 
PPT
Chapter09-10.PPT
shubhamshukla9769280
 
PDF
9. pointer, pointer & function
웅식 전
 
Address, Pointers, Arrays, and Structures.pptx
Dr. Amna Mohamed
 
Data Structure & aaplications_Module-1.pptx
GIRISHKUMARBC1
 
pointers CP Lecture.ppt
EC42ShaikhAmaan
 
CSE 1102 - Lecture_8 - Pointers_in_C.pptx
Salim Shadman Ankur
 
358 33 powerpoint-slides_3-pointers_chapter-3
sumitbardhan
 
Introduction to Data Structure
chouguleamruta24
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
Pointers C programming
Appili Vamsi Krishna
 
Lecture1
Muhammad Zubair
 
ch08.ppt
NewsMogul
 
Data Structure Introduction for Beginners
ramanathan2006
 
Memory Management for C and C++ _ language
23ecuos117
 
C Programming : Pointers and Arrays, Pointers and Strings
Selvaraj Seerangan
 
pointers_final.pptxxxxxxxxxxxxxxxxxxxxxx
assignmenthet
 
Pointers definition syntax structure use
dheeraj658032
 
Chapter09-10 Pointers and operations .PPT
ShalabhMishra10
 
Chapter09-10.PPT
shubhamshukla9769280
 
9. pointer, pointer & function
웅식 전
 

More from anilvarsha1 (11)

PPT
chaper-5_process_synchronization_part1.ppt
anilvarsha1
 
PPTX
Operating Systems Process scheduling 16th .pptx
anilvarsha1
 
PPT
ch1.ppt the essentials of Architecture and operating sys
anilvarsha1
 
PPT
14thjune youtube.ppt on operating systems Interupts
anilvarsha1
 
PPTX
how to design a Hardware Lock fro critical section.pptx
anilvarsha1
 
PPT
Data structures Implementation 09-structures.ppt
anilvarsha1
 
PPTX
introduction to operating systems and services.pptx
anilvarsha1
 
PPT
dataformats and data conversionscpu1.ppt
anilvarsha1
 
PPT
Process synchronization in operating systems
anilvarsha1
 
PPTX
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
PDF
Preparation Strategy to crack (13 march) (2).pdf
anilvarsha1
 
chaper-5_process_synchronization_part1.ppt
anilvarsha1
 
Operating Systems Process scheduling 16th .pptx
anilvarsha1
 
ch1.ppt the essentials of Architecture and operating sys
anilvarsha1
 
14thjune youtube.ppt on operating systems Interupts
anilvarsha1
 
how to design a Hardware Lock fro critical section.pptx
anilvarsha1
 
Data structures Implementation 09-structures.ppt
anilvarsha1
 
introduction to operating systems and services.pptx
anilvarsha1
 
dataformats and data conversionscpu1.ppt
anilvarsha1
 
Process synchronization in operating systems
anilvarsha1
 
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
Preparation Strategy to crack (13 march) (2).pdf
anilvarsha1
 
Ad

Recently uploaded (20)

PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPTX
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
MRRS Strength and Durability of Concrete
CivilMythili
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Design Thinking basics for Engineers.pdf
CMR University
 
Types of Bearing_Specifications_PPT.pptx
PranjulAgrahariAkash
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Day2 B2 Best.pptx
helenjenefa1
 
Ad

l7-pointersthroughmemoryinvarious languages.ppt

  • 1. October 29, 2024 Programming and Data Structure 1 Pointers
  • 2. October 29, 2024 Programming and Data Structure 2 Introduction • A pointer is a variable that represents the location (rather than the value) of a data item. • They have a number of useful applications. – Enables us to access a variable that is defined outside the function. – Can be used to pass information back and forth between a function and its reference point. – More efficient in handling data tables. – Reduces the length and complexity of a program. – Sometimes also increases the execution speed.
  • 3. October 29, 2024 Programming and Data Structure 3 Basic Concept • Within the computer memory, every stored data item occupies one or more contiguous memory cells. – The number of memory cells required to store a data item depends on its type (char, int, double, etc.). • Whenever we declare a variable, the system allocates memory location(s) to hold the value of the variable. – Since every byte in memory has a unique address, this location will also have its own (unique) address.
  • 4. October 29, 2024 Programming and Data Structure 4 Contd. • Consider the statement int xyz = 50; – This statement instructs the compiler to allocate a location for the integer variable xyz, and put the value 50 in that location. – Suppose that the address location chosen is 1380. xyz  variable 50  value 1380  address
  • 5. October 29, 2024 Programming and Data Structure 5 Contd. • During execution of the program, the system always associates the name xyz with the address 1380. – The value 50 can be accessed by using either the name xyz or the address 1380. • Since memory addresses are simply numbers, they can be assigned to some variables which can be stored in memory. – Such variables that hold memory addresses are called pointers. – Since a pointer is a variable, its value is also stored in some memory location.
  • 6. October 29, 2024 Programming and Data Structure 6 Contd. • Suppose we assign the address of xyz to a variable p. – p is said to point to the variable xyz. Variable Value Address xyz 50 1380 p 1380 2545 p = &xyz; 50 1380 xyz 1380 2545 p
  • 7. October 29, 2024 Programming and Data Structure 7 Accessing the Address of a Variable • The address of a variable can be determined using the ‘&’ operator. – The operator ‘&’ immediately preceding a variable returns the address of the variable. • Example: p = &xyz; – The address of xyz (1380) is assigned to p. • The ‘&’ operator can be used only with a simple variable or an array element. &distance &x[0] &x[i-2]
  • 8. October 29, 2024 Programming and Data Structure 8 Contd. • Following usages are illegal: &235 • Pointing at constant. int arr[20]; : &arr; • Pointing at array name. &(a+b) • Pointing at expression.
  • 9. October 29, 2024 Programming and Data Structure 9 Example #include <stdio.h> main() { int a; float b, c; double d; char ch; a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = ‘A’; printf (“%d is stored in location %u n”, a, &a) ; printf (“%f is stored in location %u n”, b, &b) ; printf (“%f is stored in location %u n”, c, &c) ; printf (“%ld is stored in location %u n”, d, &d) ; printf (“%c is stored in location %u n”, ch, &ch) ; }
  • 10. October 29, 2024 Programming and Data Structure 10 Output: 10 is stored in location 3221224908 2.500000 is stored in location 3221224904 12.360000 is stored in location 3221224900 12345.660000 is stored in location 3221224892 A is stored in location 3221224891 Incidentally variables a,b,c,d and ch are allocated to contiguous memory locations. a b c d ch
  • 11. October 29, 2024 Programming and Data Structure 11 Pointer Declarations • Pointer variables must be declared before we use them. • General form: data_type *pointer_name; Three things are specified in the above declaration: 1. The asterisk (*) tells that the variable pointer_name is a pointer variable. 2. pointer_name needs a memory location. 3. pointer_name points to a variable of type data_type.
  • 12. October 29, 2024 Programming and Data Structure 12 Contd. • Example: int *count; float *speed; • Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement like: int *p, xyz; : p = &xyz; – This is called pointer initialization.
  • 13. October 29, 2024 Programming and Data Structure 13 Things to Remember • Pointer variables must always point to a data item of the same type. float x; int *p; :  will result in erroneous output p = &x; • Assigning an absolute address to a pointer variable is prohibited. int *count; : count = 1268;
  • 14. October 29, 2024 Programming and Data Structure 14 Accessing a Variable Through its Pointer • Once a pointer has been assigned the address of a variable, the value of the variable can be accessed using the indirection operator (*). int a, b; int *p; : p = &a; b = *p; Equivalent to b = a
  • 15. October 29, 2024 Programming and Data Structure 15 Example 1 #include <stdio.h> main() { int a, b; int c = 5; int *p; a = 4 * (c + 5) ; p = &c; b = 4 * (*p + 5) ; printf (“a=%d b=%d n”, a, b) ; } Equivalent
  • 16. October 29, 2024 Programming and Data Structure 16 Example 2 #include <stdio.h> main() { int x, y; int *ptr; x = 10 ; ptr = &x ; y = *ptr ; printf (“%d is stored in location %u n”, x, &x) ; printf (“%d is stored in location %u n”, *&x, &x) ; printf (“%d is stored in location %u n”, *ptr, ptr) ; printf (“%d is stored in location %u n”, y, &*ptr) ; printf (“%u is stored in location %u n”, ptr, &ptr) ; printf (“%d is stored in location %u n”, y, &y) ; *ptr = 25; printf (“nNow x = %d n”, x); } *&xx ptr=&x; &x&*ptr
  • 17. October 29, 2024 Programming and Data Structure 17 Output: 10 is stored in location 3221224908 10 is stored in location 3221224908 10 is stored in location 3221224908 10 is stored in location 3221224908 3221224908 is stored in location 3221224900 10 is stored in location 3221224904 Now x = 25 Address of x: 3221224908 Address of y: 3221224904 Address of ptr: 3221224900
  • 18. October 29, 2024 Programming and Data Structure 18 Pointer Expressions • Like other variables, pointer variables can be used in expressions. • If p1 and p2 are two pointers, the following statements are valid: sum = *p1 + *p2 ; prod = *p1 * *p2 ; prod = (*p1) * (*p2) ; *p1 = *p1 + 2; x = *p1 / *p2 + 5 ;
  • 19. October 29, 2024 Programming and Data Structure 19 Contd. • What are allowed in C? – Add an integer to a pointer. – Subtract an integer from a pointer. – Subtract one pointer from another (related). • If p1 and p2 are both pointers to the same array, them p2–p1 gives the number of elements between p1 and p2. • What are not allowed? – Add two pointers. p1 = p1 + p2 ; – Multiply / divide a pointer in an expression. p1 = p2 / 5 ; p1 = p1 – p2 * 10 ;
  • 20. October 29, 2024 Programming and Data Structure 20 Scale Factor • We have seen that an integer value can be added to or subtracted from a pointer variable. int *p1, *p2 ; int i, j; : p1 = p1 + 1 ; p2 = p1 + j ; p2++ ; p2 = p2 – (i + j) ; • In reality, it is not the integer value which is added/subtracted, but rather the scale factor times the value.
  • 21. October 29, 2024 Programming and Data Structure 21 Contd. Data Type Scale Factor char 1 int 4 float 4 double 8 – If p1 is an integer pointer, then p1++ will increment the value of p1 by 4.
  • 22. October 29, 2024 Programming and Data Structure 22 Example: to find the scale factors #include <stdio.h> main() { printf (“Number of bytes occupied by int is %d n”, sizeof(int)); printf (“Number of bytes occupied by float is %d n”, sizeof(float)); printf (“Number of bytes occupied by double is %d n”, sizeof(double)); printf (“Number of bytes occupied by char is %d n”, sizeof(char)); } Output: Number of bytes occupied by int is 4 Number of bytes occupied by float is 4 Number of bytes occupied by double is 8 Number of bytes occupied by char is 1 Returns no. of bytes required for data type representation
  • 23. October 29, 2024 Programming and Data Structure 23 Example: Sort 3 integers • Three-step algorithm: 1. Read in three integers x, y and z 2. Put smallest in x • Swap x, y if necessary; then swap x, z if necessary. 3. Put second smallest in y • Swap y, z if necessary.
  • 24. October 29, 2024 Programming and Data Structure 24 Contd. #include <stdio.h> main() { int x, y, z ; ……….. scanf (“%d %d %d”, &x, &y, &z) ; if (x > y) swap (&x, &y); if (x > z) swap (&x, &z); if (y > z) swap (&y, &z) ; ……….. }
  • 25. October 29, 2024 Programming and Data Structure 25 Dynamic Memory Allocation
  • 26. October 29, 2024 Programming and Data Structure 26 Basic Idea • Many a time we face situations where data is dynamic in nature. – Amount of data cannot be predicted beforehand. – Number of data item keeps changing during program execution. • Such situations can be handled more easily and effectively using dynamic memory management techniques.
  • 27. October 29, 2024 Programming and Data Structure 27 Contd. • C language requires the number of elements in an array to be specified at compile time. – Often leads to wastage or memory space or program failure. • Dynamic Memory Allocation – Memory space required can be specified at the time of execution. – C supports allocating and freeing memory dynamically using library routines.
  • 28. October 29, 2024 Programming and Data Structure 28 Memory Allocation Process in C Local variables Free memory Global variables Instructions Permanent storage area Stack Heap
  • 29. October 29, 2024 Programming and Data Structure 29 Contd. • The program instructions and the global variables are stored in a region known as permanent storage area. • The local variables are stored in another area called stack. • The memory space between these two areas is available for dynamic allocation during execution of the program. – This free region is called the heap. – The size of the heap keeps changing
  • 30. October 29, 2024 Programming and Data Structure 30 Memory Allocation Functions • malloc – Allocates requested number of bytes and returns a pointer to the first byte of the allocated space. • calloc – Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. • free Frees previously allocated space. • realloc – Modifies the size of previously allocated space.
  • 31. October 29, 2024 Programming and Data Structure 31 Allocating a Block of Memory • A block of memory can be allocated using the function malloc. – Reserves a block of memory of specified size and returns a pointer of type void. – The return pointer can be assigned to any pointer type. • General format: ptr = (type *) malloc (byte_size) ;
  • 32. October 29, 2024 Programming and Data Structure 32 Contd. • Examples p = (int *) malloc (100 * sizeof (int)) ; • A memory space equivalent to “100 times the size of an int” bytes is reserved. • The address of the first byte of the allocated memory is assigned to the pointer p of type int. p 400 bytes of space
  • 33. October 29, 2024 Programming and Data Structure 33 Contd. cptr = (char *) malloc (20) ; • Allocates 10 bytes of space for the pointer cptr of type char. sptr = (struct stud *) malloc (10 * sizeof (struct stud));
  • 34. October 29, 2024 Programming and Data Structure 34 Points to Note • malloc always allocates a block of contiguous bytes. – The allocation can fail if sufficient contiguous memory space is not available. – If it fails, malloc returns NULL.
  • 35. October 29, 2024 Programming and Data Structure 35 Example printf("Input heights for %d students n",N); for(i=0;i<N;i++) scanf("%f",&height[i]); for(i=0;i<N;i++) sum+=height[i]; avg=sum/(float) N; printf("Average height= %f n", avg); } #include <stdio.h> main() { int i,N; float *height; float sum=0,avg; printf("Input the number of students. n"); scanf("%d",&N); height=(float *) malloc(N * sizeof(float)); Input the number of students. 5 Input heights for 5 students 23 24 25 26 27 Average height= 25.000000
  • 36. October 29, 2024 Programming and Data Structure 36 Releasing the Used Space • When we no longer need the data stored in a block of memory, we may release the block for future use. • How? – By using the free function. • General format: free (ptr) ; where ptr is a pointer to a memory block which has been already created using malloc.
  • 37. October 29, 2024 Programming and Data Structure 37 Altering the Size of a Block • Sometimes we need to alter the size of some previously allocated memory block. – More memory needed. – Memory allocated is larger than necessary. • How? – By using the realloc function. • If the original allocation is done by the statement ptr = malloc (size) ; then reallocation of space may be done as ptr = realloc (ptr, newsize) ;
  • 38. October 29, 2024 Programming and Data Structure 38 Contd. – The new memory block may or may not begin at the same place as the old one. • If it does not find space, it will create it in an entirely different region and move the contents of the old block into the new block. – The function guarantees that the old data remains intact. – If it is unable to allocate, it returns NULL and frees the original block.
  • 39. October 29, 2024 Programming and Data Structure 39 Pointer to Pointer • Example: int **p; p=(int **) malloc(3 * sizeof(int *)); p p[2] p[1] p[0] int * int ** int * int *
  • 40. October 29, 2024 Programming and Data Structure 40 2-D Array Allocation #include <stdio.h> #include <stdlib.h> int **allocate(int h, int w) { int **p; int i,j; p=(int **) calloc(h, sizeof (int *) ); for(i=0;i<h;i++) p[i]=(int *) calloc(w,sizeof (int)); return(p); } void read_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) scanf ("%d",&p[i][j]); } Allocate array of pointers Allocate array of integers for each row Elements accessed like 2-D array elements.
  • 41. October 29, 2024 Programming and Data Structure 41 void print_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) { for(j=0;j<w;j++) printf("%5d ",p[i][j]); printf("n"); } } 2-D Array: Contd. main() { int **p; int M,N; printf("Give M and N n"); scanf("%d%d",&M,&N); p=allocate(M,N); read_data(p,M,N); printf("n The array read as n"); print_data(p,M,N); } Give M and N 3 3 1 2 3 4 5 6 7 8 9 The array read as 1 2 3 4 5 6 7 8 9
  • 42. October 29, 2024 Programming and Data Structure 42 Linked List :: Basic Concepts • A list refers to a set of items organized sequentially. – An array is an example of a list. • The array index is used for accessing and manipulation of array elements. – Problems with array: • The array size has to be specified at the beginning. • Deleting an element or inserting an element may require shifting of elements.
  • 43. October 29, 2024 Programming and Data Structure 43 Contd. • A completely different way to represent a list: – Make each item in the list part of a structure. – The structure also contains a pointer or link to the structure containing the next item. – This type of list is called a linked list. Structure 1 item Structure 2 item Structure 3 item
  • 44. October 29, 2024 Programming and Data Structure 44 Contd. • Each structure of the list is called a node, and consists of two fields: – One containing the item. – The other containing the address of the next item in the list. • The data items comprising a linked list need not be contiguous in memory. – They are ordered by logical links that are stored as part of the data in the structure itself. – The link is a pointer to another structure of the same type.
  • 45. October 29, 2024 Programming and Data Structure 45 Contd. • Such a structure can be represented as: struct node { int item; struct node *next; } ; • Such structures which contain a member field pointing to the same structure type are called self-referential structures. item node next
  • 46. October 29, 2024 Programming and Data Structure 46 Contd. • In general, a node may be represented as follows: struct node_name { type member1; type member2; ……… struct node_name *next; };
  • 47. October 29, 2024 Programming and Data Structure 47 Illustration • Consider the structure: struct stud { int roll; char name[30]; int age; struct stud *next; }; • Also assume that the list consists of three nodes n1, n2 and n3. struct stud n1, n2, n3;
  • 48. October 29, 2024 Programming and Data Structure 48 Contd. • To create the links between nodes, we can write: n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* No more nodes follow */ • Now the list looks like: n1 n2 n3 roll name age next
  • 49. October 29, 2024 Programming and Data Structure 49 Example #include <stdio.h> struct stud { int roll; char name[30]; int age; struct stud *next; }; main() { struct stud n1, n2, n3; struct stud *p; scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age); scanf (“%d %s %d”, &n2.roll, n2.name, &n2.age); scanf (“%d %s %d”, &n3.roll, n3.name, &n3.age); n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* Now traverse the list and print the elements */ p = n1 ; /* point to 1st element */ while (p != NULL) { printf (“n %d %s %d”, p->roll, p->name, p->age); p = p->next; } }