SlideShare a Scribd company logo
Introduc)on to Pointer Variables
Chapter 2
Pointer Variables
• Pointer variables are an important concept and one
that’s tradi5onally difficult to grasp at first
• Programming with pointer variables in C/C++ is a
double-edge sword
– They can be extremely useful and flexible
– Misuses of pointers can lead to both bizarre effects and very
subtle errors
2
Random Access Memory
• A computer’s memory, also known as random access
memory (RAM), consists of a sequence of bytes
• Each byte of memory has an unique address
– Physically, computer addresses start with zero and con?nue
up, one at a ?me, un?l they reach the highest address
3
A computer’s memory, also known as random access memory (RAM), consists
of a sequence of bytes.
For example: 1MB of RAM has exactly 220
(or 1,048,576) bytes of memory,
1GB of RAM has exactly 230
(or 1,073,741,824) bytes of memory. My laptop has 8GB
of RAM so it has exactly 8x230
(or 8,589,934,592) bytes of memory.
Each byte of memory has a unique address. Computer addresses typically start
with zero and continue up, one at a time, until they reach the highest address. The first
byte has an address of 0, the next byte has an address of 1, and so on.
The following figure shows the addressing scheme for a computer with 1GB of
RAM. Notice that the addresses run from 0 (the lowest address) all the way up to
1,073,741,823 (the highest address).
00110000 10000000 00100100 … 01110010 00000000 00110011
<0> <1> <2> … <1,073,741,821> <1,073,741,822> <1,073,741,823>
Note: For distinguishing purposes/clearity of vision, an address is always surrounded
Address of a Variable
• At run-5me, every variable is allocated a block of
memory
– A block is a sequence of consecu?ve bytes and it’s large
enough to hold a value of the variable’s data type
• A variable’s address is the address of the first byte
allocated to that variable
– In other words, a variable’s address is the star?ng address of
the block of memory allocated to that variable
4
addresses 984, 985, 986, 987.
int b
00110011 10110010 01110010 00000000
<0> … <984> <985> <986> <987> …
•! The sizeof operator
The sizeof operator is typically followed by a pair of parentheses surrounding
a single operand. The operand is either a type name or a variable. This operator returns
the size, in bytes, of its operand.
int a;
cout << sizeof(a) << sizeof(char) << sizeof(float);
•! The & (ampersand, address) operator
The & operator, called the address-of operator, is a unary operator that pairs with
a variable name to produce the address of the variable.
The expression &b refers to the adress of memory allocated to b variable.
int b
00110011 10110010 01110010 00000000
<0> … <984> <985> <986> <987> …
int b;
The sizeof Operator
• The sizeof operator is typically followed by a pair of
parentheses surrounding a single operand
– The operand is either a type name or a variable
• This operator returns the size, in bytes, of its operand
5
The & Operator
• The & operator, called the address-of (or address)
operator, is a unary operator that pairs with a variable
name to produce the address of the variable
• In prac5ce, we do not need to know or use the physical
address of a variable
6
Pointer Variables
• A pointer variable, or pointer for short, is a special
variable, specifically designed to hold a memory address
• Defini5on of a pointer variable:
<typename> * <pointer variable name>;
int * pi;
– pi is a pointer to type int
➡ pi can be used to hold the star?ng address of the block of
memory allocated to a variable of type int, or
➡ pi can be used to hold the address of a variable of type int
7
Pointer Variables
• A pointer variable, or pointer for short, is a special
variable, specifically designed to hold a memory address
• Defini5on of a pointer variable:
<typename> * <pointer variable name>;
int * pi, n; pi = &n;
– pi is the pointer to variable n (or pi points to n, or n is
pointed to by pi)
➡ The value of pi is the star?ng address of the block of memory
allocated to variable n, or
➡ The value of pi is the address of variable n 8
Pointer Variables
• A pointer variable is also a variable that requires a block
of memory
– The size of pointers is in?mately ?ed to the computer’s
processor type, OS, programming language, …
• Let’s assume that a pointer variable requires 4 bytes of
memory
9
Pointer Variables
• A pointer variable, or pointer for short, is a special
variable, specifically designed to hold a memory address
• Defini5on of a pointer variable:
<typename> * <pointer variable name>;
int * pi, n; pi = &n;
char * pc, c; pc = &c;
float * pf, f; pf = &f;
double * pd, d; pd = &d;
pi = n; n = pi; n = &pi; // Error
10
The * Operator
• The * operator, called the star operator, is a unary
operator that pairs with a pointer variable and turns it
into the variable the pointer variable points to
– It’s also called dereference pointer operator
– The & operator and the * operator are inverses of each other
int * pi, n = 5;
pi = &n;
n = *pi + 3;
*pi = 10;
11
Pointer Ini;aliza;on
• Make sure your pointer variables are ini5alized with
valid memory address
– Using an unini?alized pointer variable is the fastest, and most
common, way to crash your program
• If you don’t have a value to put in a pointer, set it to the
special value NULL (or nullptr in C++ 11)
– Now, it’s called null pointer
12
A null pointer is the one that
points to nothing
Using Pointers as Func;on Parameters
• Pointer variables can be used as func5on parameters
– Actual parameters
– Formal parameters
• The return type of a func5on can be pointer type
13
Pointer Arithme;c
• Some arithme5c opera5ons, such as addi5on or
subtrac5on, may be performed on pointer variables
• Adding one to a pointer variable increases its value by
the size (in byte) of the type to which it points
pi = pi + 1;
pc = pc – n;
pf++;
pd -= n;
14
Pointer Arithme;c
• Some arithme5c opera5ons, such as addi5on or
subtrac5on, may be performed on pointer variables
• Adding one to a pointer variable increases its value by
the size (in byte) of the type to which it points
• Two pointers of the same type can be subtracted from
each other
int * pi, * qi, n;
…
n = pi – qi;
15
Pointer Arithme;c
• Some arithme5c opera5ons, such as addi5on or
subtrac5on, may be performed on pointer variables
• Adding one to a pointer variable increases its value by
the size (in byte) of the type to which it points
• Two pointers of the same type can be subtracted from
each other
• Two pointers of the same type may be compared by
using any of C/C++’s rela5onal operators
16
Constant Pointers and Pointers to Constants
• A pointer to constant points to a constant item
– The data that the pointer points to cannot change, but the
pointer itself can change
int i = 5, j = 10;
const int * q;
q = &j;
j++;
*q = 20; // Error
q = &i;
17
Constant Pointers and Pointers to Constants
• A constant pointer is the pointer itself that is constant
– It must be ini?alized with a star?ng value (an address) and it
cannot point to anything else
int i = 5, j = 10;
int * const p = &i, * q;
q = &j;
p = q; // Error
p++; // Error
*p = *q + 5;
18
Constant Pointers and Pointers to Constants
• A constant pointer to constant is a pointer that can
neither change its value and nor can change the data it
points to
int i = 5, j = 10;
const int * const r = &i;
int * q = &j;
i++;
r++; // Error
*r = 20; // Error
r = q; // Error 19
Pointers and One-Dimensional Arrays
• An array name is a constant pointer poin5ng to the first
element of the array
– The name of an array is interpreted as the address of the first
element of the array
int a[10], * p, * q;
p = a; p++; p = a + 1;
a = p; a++; // Error
q = &a[5]; cout << q – p;
p[0] = p[1];
20
21
Example
Find the distance between the largest and the smallest
elements in an array of 𝑛 dis5nct numbers
Pointers and Two-Dimensional Arrays
• Representa5on of a two-dimensional array in memory is
a linear sequence of consecu5ve bytes
int a[M][N];
– Variable a is a constant pointer poin?ng to the first element
of a linear sequence of MxN ints in memory
– The type of a[i][j] is int
– The type of a[i] is equivalent to a constant pointer to int
– The type of a is equivalent to a constant pointer to int but an
explicit cast is necessary
22
Dynamic Memory Alloca;on
• The size of the problem oTen cannot be determined at
compile-4me
• Dynamic memory alloca4on is the technique of
alloca5ng and freeing memory at run-5me
• Dynamically allocated memory must be referred to by
pointers
23
Dynamic Memory Alloca;on – the Syntax
24
• In C programming language:
void * malloc(<size>);
– The func?on allocates a block of <size> bytes of memory
and returns a pointer to the beginning of the block
– If the func?on failed to allocate the requested block of
memory, value NULL is returned
free(<pointer>);
– The func?on deallocates a block of memory previously
allocated by a call to malloc, calloc or realloc
Dynamic Memory Alloca;on – the Syntax
25
• In C++ programming language:
<pointer var.> = new <type>;
– The operator new allocates memory of type <type>
<pointer var.> = new <type> [<size>];
– The operator new is also used to allocate an array of memory
of type <type>
delete <pointer>;
delete [] <pointer>;
– The operator delete deallocates a block of memory
previously allocated by the new operator
Example
26

More Related Content

PDF
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
PPT
Pointer
manish840
 
PDF
A small presentation on Pointers in C ++
RahulRutton
 
PDF
Pointers by: Professor Lili Saghafi
Professor Lili Saghafi
 
PPT
Pointers (Pp Tminimizer)
tech4us
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPT
Pointers definition syntax structure use
dheeraj658032
 
PPT
Chapter09-10 Pointers and operations .PPT
ShalabhMishra10
 
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
Pointer
manish840
 
A small presentation on Pointers in C ++
RahulRutton
 
Pointers by: Professor Lili Saghafi
Professor Lili Saghafi
 
Pointers (Pp Tminimizer)
tech4us
 
Pointer in C++
Mauryasuraj98
 
Pointers definition syntax structure use
dheeraj658032
 
Chapter09-10 Pointers and operations .PPT
ShalabhMishra10
 

Similar to Chapter 2 - Introduction to Pointer Variables - Student.pdf (20)

PPT
Chapter09-10.PPT
shubhamshukla9769280
 
PDF
0-Slot11-12-Pointers.pdf
ssusere19c741
 
PPTX
Pointers in c++
sai tarlekar
 
PDF
C Pointers
omukhtar
 
PPTX
Used of Pointer in C++ Programming
Abdullah Jan
 
PDF
Pointers
Swarup Boro
 
PPTX
COM1407: Working with Pointers
Hemantha Kulathilake
 
PPT
Lecture2.ppt
Sabaunnisa3
 
PDF
C++ computer language chapter 4 pointers.pdf
birukh36
 
PPTX
9781337102087 ppt ch12
Terry Yoast
 
PPTX
C pointer
University of Potsdam
 
PPT
POINTERS IN C++ CBSE +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
PPT
Pointer
Fahuda E
 
PDF
Pointers
Swarup Kumar Boro
 
PPTX
Pointers in c language
Tanmay Modi
 
PPTX
Pointers in c v5 12102017 1
tanmaymodi4
 
PPT
C/C++ Pointers explanationwith different examples
ulhaq18
 
PDF
VIT351 Software Development VI Unit3
YOGESH SINGH
 
PPT
Pointers_in_c.pptfffgfggdggffffrreeeggttr
MorfaSafi
 
Chapter09-10.PPT
shubhamshukla9769280
 
0-Slot11-12-Pointers.pdf
ssusere19c741
 
Pointers in c++
sai tarlekar
 
C Pointers
omukhtar
 
Used of Pointer in C++ Programming
Abdullah Jan
 
Pointers
Swarup Boro
 
COM1407: Working with Pointers
Hemantha Kulathilake
 
Lecture2.ppt
Sabaunnisa3
 
C++ computer language chapter 4 pointers.pdf
birukh36
 
9781337102087 ppt ch12
Terry Yoast
 
POINTERS IN C++ CBSE +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Pointer
Fahuda E
 
Pointers in c language
Tanmay Modi
 
Pointers in c v5 12102017 1
tanmaymodi4
 
C/C++ Pointers explanationwith different examples
ulhaq18
 
VIT351 Software Development VI Unit3
YOGESH SINGH
 
Pointers_in_c.pptfffgfggdggffffrreeeggttr
MorfaSafi
 
Ad

Recently uploaded (20)

PDF
717629748-Databricks-Certified-Data-Engineer-Professional-Dumps-by-Ball-21-03...
pedelli41
 
PDF
Practical Measurement Systems Analysis (Gage R&R) for design
Rob Schubert
 
PPTX
Power BI in Business Intelligence with AI
KPR Institute of Engineering and Technology
 
PDF
oop_java (1) of ice or cse or eee ic.pdf
sabiquntoufiqlabonno
 
PPTX
lecture 13 mind test academy it skills.pptx
ggesjmrasoolpark
 
PPTX
Presentation (1) (1).pptx k8hhfftuiiigff
karthikjagath2005
 
PPTX
Probability systematic sampling methods.pptx
PrakashRajput19
 
PDF
An Uncut Conversation With Grok | PDF Document
Mike Hydes
 
PPTX
Multiscale Segmentation of Survey Respondents: Seeing the Trees and the Fores...
Sione Palu
 
PPTX
Fuzzy_Membership_Functions_Presentation.pptx
pythoncrazy2024
 
PPTX
Introduction to Data Analytics and Data Science
KavithaCIT
 
PPTX
Data Security Breach: Immediate Action Plan
varmabhuvan266
 
PDF
Classifcation using Machine Learning and deep learning
bhaveshagrawal35
 
PPTX
Databricks-DE-Associate Certification Questions-june-2024.pptx
pedelli41
 
PDF
Blue Futuristic Cyber Security Presentation.pdf
tanvikhunt1003
 
PDF
SUMMER INTERNSHIP REPORT[1] (AutoRecovered) (6) (1).pdf
pandeydiksha814
 
PPTX
The whitetiger novel review for collegeassignment.pptx
DhruvPatel754154
 
PPTX
Complete_STATA_Introduction_Beginner.pptx
mbayekebe
 
PPTX
Introduction-to-Python-Programming-Language (1).pptx
dhyeysapariya
 
PDF
Technical Writing Module-I Complete Notes.pdf
VedprakashArya13
 
717629748-Databricks-Certified-Data-Engineer-Professional-Dumps-by-Ball-21-03...
pedelli41
 
Practical Measurement Systems Analysis (Gage R&R) for design
Rob Schubert
 
Power BI in Business Intelligence with AI
KPR Institute of Engineering and Technology
 
oop_java (1) of ice or cse or eee ic.pdf
sabiquntoufiqlabonno
 
lecture 13 mind test academy it skills.pptx
ggesjmrasoolpark
 
Presentation (1) (1).pptx k8hhfftuiiigff
karthikjagath2005
 
Probability systematic sampling methods.pptx
PrakashRajput19
 
An Uncut Conversation With Grok | PDF Document
Mike Hydes
 
Multiscale Segmentation of Survey Respondents: Seeing the Trees and the Fores...
Sione Palu
 
Fuzzy_Membership_Functions_Presentation.pptx
pythoncrazy2024
 
Introduction to Data Analytics and Data Science
KavithaCIT
 
Data Security Breach: Immediate Action Plan
varmabhuvan266
 
Classifcation using Machine Learning and deep learning
bhaveshagrawal35
 
Databricks-DE-Associate Certification Questions-june-2024.pptx
pedelli41
 
Blue Futuristic Cyber Security Presentation.pdf
tanvikhunt1003
 
SUMMER INTERNSHIP REPORT[1] (AutoRecovered) (6) (1).pdf
pandeydiksha814
 
The whitetiger novel review for collegeassignment.pptx
DhruvPatel754154
 
Complete_STATA_Introduction_Beginner.pptx
mbayekebe
 
Introduction-to-Python-Programming-Language (1).pptx
dhyeysapariya
 
Technical Writing Module-I Complete Notes.pdf
VedprakashArya13
 
Ad

Chapter 2 - Introduction to Pointer Variables - Student.pdf

  • 1. Introduc)on to Pointer Variables Chapter 2
  • 2. Pointer Variables • Pointer variables are an important concept and one that’s tradi5onally difficult to grasp at first • Programming with pointer variables in C/C++ is a double-edge sword – They can be extremely useful and flexible – Misuses of pointers can lead to both bizarre effects and very subtle errors 2
  • 3. Random Access Memory • A computer’s memory, also known as random access memory (RAM), consists of a sequence of bytes • Each byte of memory has an unique address – Physically, computer addresses start with zero and con?nue up, one at a ?me, un?l they reach the highest address 3 A computer’s memory, also known as random access memory (RAM), consists of a sequence of bytes. For example: 1MB of RAM has exactly 220 (or 1,048,576) bytes of memory, 1GB of RAM has exactly 230 (or 1,073,741,824) bytes of memory. My laptop has 8GB of RAM so it has exactly 8x230 (or 8,589,934,592) bytes of memory. Each byte of memory has a unique address. Computer addresses typically start with zero and continue up, one at a time, until they reach the highest address. The first byte has an address of 0, the next byte has an address of 1, and so on. The following figure shows the addressing scheme for a computer with 1GB of RAM. Notice that the addresses run from 0 (the lowest address) all the way up to 1,073,741,823 (the highest address). 00110000 10000000 00100100 … 01110010 00000000 00110011 <0> <1> <2> … <1,073,741,821> <1,073,741,822> <1,073,741,823> Note: For distinguishing purposes/clearity of vision, an address is always surrounded
  • 4. Address of a Variable • At run-5me, every variable is allocated a block of memory – A block is a sequence of consecu?ve bytes and it’s large enough to hold a value of the variable’s data type • A variable’s address is the address of the first byte allocated to that variable – In other words, a variable’s address is the star?ng address of the block of memory allocated to that variable 4 addresses 984, 985, 986, 987. int b 00110011 10110010 01110010 00000000 <0> … <984> <985> <986> <987> … •! The sizeof operator The sizeof operator is typically followed by a pair of parentheses surrounding a single operand. The operand is either a type name or a variable. This operator returns the size, in bytes, of its operand. int a; cout << sizeof(a) << sizeof(char) << sizeof(float); •! The & (ampersand, address) operator The & operator, called the address-of operator, is a unary operator that pairs with a variable name to produce the address of the variable. The expression &b refers to the adress of memory allocated to b variable. int b 00110011 10110010 01110010 00000000 <0> … <984> <985> <986> <987> … int b;
  • 5. The sizeof Operator • The sizeof operator is typically followed by a pair of parentheses surrounding a single operand – The operand is either a type name or a variable • This operator returns the size, in bytes, of its operand 5
  • 6. The & Operator • The & operator, called the address-of (or address) operator, is a unary operator that pairs with a variable name to produce the address of the variable • In prac5ce, we do not need to know or use the physical address of a variable 6
  • 7. Pointer Variables • A pointer variable, or pointer for short, is a special variable, specifically designed to hold a memory address • Defini5on of a pointer variable: <typename> * <pointer variable name>; int * pi; – pi is a pointer to type int ➡ pi can be used to hold the star?ng address of the block of memory allocated to a variable of type int, or ➡ pi can be used to hold the address of a variable of type int 7
  • 8. Pointer Variables • A pointer variable, or pointer for short, is a special variable, specifically designed to hold a memory address • Defini5on of a pointer variable: <typename> * <pointer variable name>; int * pi, n; pi = &n; – pi is the pointer to variable n (or pi points to n, or n is pointed to by pi) ➡ The value of pi is the star?ng address of the block of memory allocated to variable n, or ➡ The value of pi is the address of variable n 8
  • 9. Pointer Variables • A pointer variable is also a variable that requires a block of memory – The size of pointers is in?mately ?ed to the computer’s processor type, OS, programming language, … • Let’s assume that a pointer variable requires 4 bytes of memory 9
  • 10. Pointer Variables • A pointer variable, or pointer for short, is a special variable, specifically designed to hold a memory address • Defini5on of a pointer variable: <typename> * <pointer variable name>; int * pi, n; pi = &n; char * pc, c; pc = &c; float * pf, f; pf = &f; double * pd, d; pd = &d; pi = n; n = pi; n = &pi; // Error 10
  • 11. The * Operator • The * operator, called the star operator, is a unary operator that pairs with a pointer variable and turns it into the variable the pointer variable points to – It’s also called dereference pointer operator – The & operator and the * operator are inverses of each other int * pi, n = 5; pi = &n; n = *pi + 3; *pi = 10; 11
  • 12. Pointer Ini;aliza;on • Make sure your pointer variables are ini5alized with valid memory address – Using an unini?alized pointer variable is the fastest, and most common, way to crash your program • If you don’t have a value to put in a pointer, set it to the special value NULL (or nullptr in C++ 11) – Now, it’s called null pointer 12 A null pointer is the one that points to nothing
  • 13. Using Pointers as Func;on Parameters • Pointer variables can be used as func5on parameters – Actual parameters – Formal parameters • The return type of a func5on can be pointer type 13
  • 14. Pointer Arithme;c • Some arithme5c opera5ons, such as addi5on or subtrac5on, may be performed on pointer variables • Adding one to a pointer variable increases its value by the size (in byte) of the type to which it points pi = pi + 1; pc = pc – n; pf++; pd -= n; 14
  • 15. Pointer Arithme;c • Some arithme5c opera5ons, such as addi5on or subtrac5on, may be performed on pointer variables • Adding one to a pointer variable increases its value by the size (in byte) of the type to which it points • Two pointers of the same type can be subtracted from each other int * pi, * qi, n; … n = pi – qi; 15
  • 16. Pointer Arithme;c • Some arithme5c opera5ons, such as addi5on or subtrac5on, may be performed on pointer variables • Adding one to a pointer variable increases its value by the size (in byte) of the type to which it points • Two pointers of the same type can be subtracted from each other • Two pointers of the same type may be compared by using any of C/C++’s rela5onal operators 16
  • 17. Constant Pointers and Pointers to Constants • A pointer to constant points to a constant item – The data that the pointer points to cannot change, but the pointer itself can change int i = 5, j = 10; const int * q; q = &j; j++; *q = 20; // Error q = &i; 17
  • 18. Constant Pointers and Pointers to Constants • A constant pointer is the pointer itself that is constant – It must be ini?alized with a star?ng value (an address) and it cannot point to anything else int i = 5, j = 10; int * const p = &i, * q; q = &j; p = q; // Error p++; // Error *p = *q + 5; 18
  • 19. Constant Pointers and Pointers to Constants • A constant pointer to constant is a pointer that can neither change its value and nor can change the data it points to int i = 5, j = 10; const int * const r = &i; int * q = &j; i++; r++; // Error *r = 20; // Error r = q; // Error 19
  • 20. Pointers and One-Dimensional Arrays • An array name is a constant pointer poin5ng to the first element of the array – The name of an array is interpreted as the address of the first element of the array int a[10], * p, * q; p = a; p++; p = a + 1; a = p; a++; // Error q = &a[5]; cout << q – p; p[0] = p[1]; 20
  • 21. 21 Example Find the distance between the largest and the smallest elements in an array of 𝑛 dis5nct numbers
  • 22. Pointers and Two-Dimensional Arrays • Representa5on of a two-dimensional array in memory is a linear sequence of consecu5ve bytes int a[M][N]; – Variable a is a constant pointer poin?ng to the first element of a linear sequence of MxN ints in memory – The type of a[i][j] is int – The type of a[i] is equivalent to a constant pointer to int – The type of a is equivalent to a constant pointer to int but an explicit cast is necessary 22
  • 23. Dynamic Memory Alloca;on • The size of the problem oTen cannot be determined at compile-4me • Dynamic memory alloca4on is the technique of alloca5ng and freeing memory at run-5me • Dynamically allocated memory must be referred to by pointers 23
  • 24. Dynamic Memory Alloca;on – the Syntax 24 • In C programming language: void * malloc(<size>); – The func?on allocates a block of <size> bytes of memory and returns a pointer to the beginning of the block – If the func?on failed to allocate the requested block of memory, value NULL is returned free(<pointer>); – The func?on deallocates a block of memory previously allocated by a call to malloc, calloc or realloc
  • 25. Dynamic Memory Alloca;on – the Syntax 25 • In C++ programming language: <pointer var.> = new <type>; – The operator new allocates memory of type <type> <pointer var.> = new <type> [<size>]; – The operator new is also used to allocate an array of memory of type <type> delete <pointer>; delete [] <pointer>; – The operator delete deallocates a block of memory previously allocated by the new operator