SlideShare a Scribd company logo
Pointers
Michael Heron
Introduction
• One of the trickiest things in C++ to get your heads around is
the topic of pointers.
• I want to introduce this subject early so it doesn’t become a huge
problem down the line.
• We don’t need to do an awful lot of pointer work at the
moment.
• We’ll need to do more in the future.
• Pointers eventually become second nature.
• Honest
Cube Calculator
#include <iostream>
using namespace std;
void calculate_cube (int num) {
num = num * num * num;
}
int main() {
int num = 5;
calculate_cube(num);
cout << "Cube is " << num << endl;
return 1;
}
Cube Calculator
• What will the output of this program be?
• We create a variable
• We pass that variable to our function
• We make that variable equal the cube of itself.
• It seems like the answer should be 125…
• … but it won’t be.
• Why?
Functions and Variables
• We have spoken about functions in an earlier lecture.
• And how we can provide information to functions by passing
parameters.
• When we do this, what we pass into the function is a copy of
the data we have.
• So we really have two versions of the same data in the program at
any one time.
Functions and Variables
• In our calculate_cube function, we are working with a copy of
num.
• We are never directly manipulating the value of num itself.
• This is known as passing by value.
• We pass the value of a variable, not the variable itself.
• Every variable in C++ is stored in the computer’s memory.
• Sometimes we want to be able to get to that memory location.
• We want to pass things by reference.
Pointers
• Here is where the pointer enters our discussion.
• It points to a memory location.
• Pointers come with two new syntax elements to learn.
• & which is the reference operator
• * which is the dereference operator.
• We use these to swap between the memory location and the
value of a memory location.
Reference Operator
• The & symbol is our reference operator.
• You can think of it as meaning ‘the address of’
• We can use this to say ‘I want to send a memory location into
this function’:
int main() {
int num = 5;
calculate_cube(&num);
cout << "Cube is " << num << endl;
return 1;
}
Dereference Operator
• * is the dereference operator
• Think of it as ‘the value of’
• We also use this to indicate that a variable is going to be a
pointer.
• When we accept the parameter we are given, we want to be
able to indicate we are working with a pointer.
• We need to change our function a little to accommodate that:
Our Program With Pointers
#include <iostream>
using namespace std;
void calculate_cube (int *num) {
*num = *num * *num * *num;
}
int main() {
int num = 5;
calculate_cube(&num);
cout << "Cube is " << num << endl;
return 1;
}
How Do They Work?
• Every variable takes up a certain amount of memory.
• This varies from type to type.
• Each variable has a memory address.
• That’s how the computer knows where to find it in memory.
• A pointer is a location in memory that contains the memory
address of another location.
• This is known as indirection.
Alternative Syntax
#include <iostream>
using namespace std;
void calculate_square (int &num) {
num = num * num;
}
int main() {
int num = 5;
int num2 = 10;
calculate_square (num2);
cout << "Square is " << num2 << endl;
return 1;
}
Do We Want Them?
• Yes and no.
• They are invaluable for doing certain things.
• They are overly complex for many requirements.
• Far better method in most cases to avoid the use of pointers
and make use of return values.
• This is not possible in all situations.
• When in doubt, try to think of a way to avoid using a pointer.
Why Use Pointers?
• Very efficient.
• Copying values, especially things like objects, is very costly.
• More on this in a later lecture.
• Permits functions that return more than one value.
• Canonical example of this is a function that swaps the contents of
two variables.
• Resolves some issues of data persistance.
• Introduces others along the way…
Why Not Use Pointers?
• Additional complexity of code.
• Code that uses pointers is almost always more complex.
• Easy to make mistakes.
• Pointers let you work with the live ammo of memory addresses.
• You can easily manipulate the memory location rather than the
memory contents.
• Permits unintended side effects.
• Largely negates the issue of scope.
Alas…
• Sometimes, we have to use pointers.
• Because C++ is built around the assumption we will be.
• We’ll see them used relatively freely when we talk about
objects in a couple of weeks.
• For various reasons, passing by value is not really appropriate for
dealing with objects.
Pointer Notation
• When we want to represent pointers in diagram form, we use
the notation below.
• This is a simple representation.
• We don’t worry about memory locations
• Just the relationship between variables.
*ptr Var
Pointers Example 1
int main() {
int *yPtr, *zPtr;
int y, z;
y = 10;
z = 5;
zPtr = &z;
yPtr = &y;
cout << "Y is " << y << endl;
cout << "yPtr is " << yPtr<< endl;
cout << "Z is " << z<< endl;
cout << "zPtr is " << zPtr<< endl;
return 1;
}
Pointers Example 2
int main() {
int *yPtr, *zPtr;
int y, z;
y = 10;
z = 5;
zPtr = &z;
yPtr = &y;
cout << "Y is " << &y << endl;
cout << "yPtr is " << *yPtr<< endl;
cout << "Z is " << &z << endl;
cout << "zPtr is " << *zPtr<< endl;
return 1;
}
Pointers Example 3
int main() {
int *yPtr, *zPtr;
int y, z;
y = 10;
z = 5;
zPtr = &z;
yPtr = zPtr;
*zPtr = 20;
cout << "yPtr is " << *yPtr<< endl;
cout << "zPtr is " << *zPtr<< endl;
return 1;
}
When Working With Pointers
• Always be clear of the relationship between variables.
• Draw diagrams if needed
• Always be sure of where your pointers are actually pointing.
• Remember, the * means ‘the value of my current memory
location’
• Be wary of side effects
• Very easy to introduce!
Summary
• C++ has pointers.
• Don’t sweat it too much just now…
• They are extremely powerful
• They let you do things you couldn’t really otherwise do.
• They are extremely dangerous.
• It’s very easy to lose control of your program by using them.
• Be wary!

More Related Content

PDF
Functional Objects in Ruby: new horizons – Valentine Ostakh
Ruby Meditation
 
PPTX
Function Parameters
primeteacher32
 
PPTX
Inline Functions and Default arguments
Nikhil Pandit
 
PPT
Unit 6 pointers
George Erfesoglou
 
PPTX
Inline function
Tech_MX
 
PPTX
C++ Pointers
Chaand Sheikh
 
PPTX
C++ programming function
Vishalini Mugunen
 
PPTX
Inline function in C++
Learn By Watch
 
Functional Objects in Ruby: new horizons – Valentine Ostakh
Ruby Meditation
 
Function Parameters
primeteacher32
 
Inline Functions and Default arguments
Nikhil Pandit
 
Unit 6 pointers
George Erfesoglou
 
Inline function
Tech_MX
 
C++ Pointers
Chaand Sheikh
 
C++ programming function
Vishalini Mugunen
 
Inline function in C++
Learn By Watch
 

What's hot (20)

PPT
Functions in c++
Maaz Hasan
 
PPTX
Functions in C++
home
 
PPTX
Lecture 4: Functions
Vivek Bhargav
 
PPT
Advanced Javascript
relay12
 
PPT
C++ Functions
sathish sak
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPT
Python Built-in Functions and Use cases
Srajan Mor
 
PPTX
Python Functions
Mohammed Sikander
 
PDF
Monad Fact #6
Philip Schwarz
 
PPTX
Function class in c++
Kumar
 
PPTX
Data weave 2.0 advanced (recursion, pattern matching)
ManjuKumara GH
 
PPTX
INLINE FUNCTION IN C++
Vraj Patel
 
PPTX
Inline functions
DhwaniHingorani
 
PPT
Functions in c++
Abdullah Turkistani
 
DOCX
Inline function(oops)
Jay Patel
 
PPTX
CPP04 - Selection
Michael Heron
 
PPT
C++ functions
Dawood Jutt
 
PPT
C++ functions
Mayank Jain
 
PDF
Refactoring
Tausun Akhtary
 
PDF
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Philip Schwarz
 
Functions in c++
Maaz Hasan
 
Functions in C++
home
 
Lecture 4: Functions
Vivek Bhargav
 
Advanced Javascript
relay12
 
C++ Functions
sathish sak
 
Functions in c++
Rokonuzzaman Rony
 
Python Built-in Functions and Use cases
Srajan Mor
 
Python Functions
Mohammed Sikander
 
Monad Fact #6
Philip Schwarz
 
Function class in c++
Kumar
 
Data weave 2.0 advanced (recursion, pattern matching)
ManjuKumara GH
 
INLINE FUNCTION IN C++
Vraj Patel
 
Inline functions
DhwaniHingorani
 
Functions in c++
Abdullah Turkistani
 
Inline function(oops)
Jay Patel
 
CPP04 - Selection
Michael Heron
 
C++ functions
Dawood Jutt
 
C++ functions
Mayank Jain
 
Refactoring
Tausun Akhtary
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Philip Schwarz
 
Ad

Similar to CPP08 - Pointers (20)

PPTX
Pointers in c++
Vineeta Garg
 
PPTX
Introduction to pointers in c plus plus .
karimibaryal1996
 
PPTX
Pointers in C++ object oriented programming
Ahmad177077
 
PDF
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
drsomeshdewangan
 
PPTX
Object Oriented Programming using C++: Ch10 Pointers.pptx
RashidFaridChishti
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPTX
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
PDF
C++ computer language chapter 4 pointers.pdf
birukh36
 
PPT
Pointer
Fahuda E
 
PPTX
Computer Programming Lecture numer 05 -- pointers,variablesb
AHMADMEHMOOD32
 
PDF
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
PPTX
Chp3(pointers ref)
Mohd Effandi
 
PPT
Advanced pointers
Koganti Ravikumar
 
PPTX
COM1407: Working with Pointers
Hemantha Kulathilake
 
PPTX
c++ pointers by Amir Hamza Khan (SZABISTIAN)
Ameer Hamxa
 
PPTX
pointer.pptx module of information technology
jolynetomas
 
PPTX
Pointers in c++
sai tarlekar
 
PPT
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Jayanshu Gundaniya
 
DOCX
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
Pointers in c++
Vineeta Garg
 
Introduction to pointers in c plus plus .
karimibaryal1996
 
Pointers in C++ object oriented programming
Ahmad177077
 
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
drsomeshdewangan
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
RashidFaridChishti
 
Pointer in C++
Mauryasuraj98
 
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
C++ computer language chapter 4 pointers.pdf
birukh36
 
Pointer
Fahuda E
 
Computer Programming Lecture numer 05 -- pointers,variablesb
AHMADMEHMOOD32
 
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
Chp3(pointers ref)
Mohd Effandi
 
Advanced pointers
Koganti Ravikumar
 
COM1407: Working with Pointers
Hemantha Kulathilake
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
Ameer Hamxa
 
pointer.pptx module of information technology
jolynetomas
 
Pointers in c++
sai tarlekar
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Jayanshu Gundaniya
 
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
Ad

More from Michael Heron (20)

PPTX
Meeple centred design - Board Game Accessibility
Michael Heron
 
PPTX
Musings on misconduct
Michael Heron
 
PDF
Accessibility Support with the ACCESS Framework
Michael Heron
 
PDF
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
PPTX
Authorship and Autership
Michael Heron
 
PDF
Text parser based interaction
Michael Heron
 
PPTX
SAD04 - Inheritance
Michael Heron
 
PPT
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
PPT
GRPHICS07 - Textures
Michael Heron
 
PPT
GRPHICS06 - Shading
Michael Heron
 
PPT
GRPHICS05 - Rendering (2)
Michael Heron
 
PPT
GRPHICS04 - Rendering (1)
Michael Heron
 
PPTX
GRPHICS03 - Graphical Representation
Michael Heron
 
PPTX
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
PPTX
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
PPT
GRPHICS09 - Art Appreciation
Michael Heron
 
PPTX
2CPP18 - Modifiers
Michael Heron
 
PPTX
2CPP17 - File IO
Michael Heron
 
PPT
2CPP16 - STL
Michael Heron
 
PPT
2CPP15 - Templates
Michael Heron
 
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Michael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
Authorship and Autership
Michael Heron
 
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
Michael Heron
 
GRPHICS05 - Rendering (2)
Michael Heron
 
GRPHICS04 - Rendering (1)
Michael Heron
 
GRPHICS03 - Graphical Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
Michael Heron
 
2CPP17 - File IO
Michael Heron
 
2CPP16 - STL
Michael Heron
 
2CPP15 - Templates
Michael Heron
 

Recently uploaded (20)

PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Presentation about variables and constant.pptx
safalsingh810
 
Activate_Methodology_Summary presentatio
annapureddyn
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 

CPP08 - Pointers

  • 2. Introduction • One of the trickiest things in C++ to get your heads around is the topic of pointers. • I want to introduce this subject early so it doesn’t become a huge problem down the line. • We don’t need to do an awful lot of pointer work at the moment. • We’ll need to do more in the future. • Pointers eventually become second nature. • Honest
  • 3. Cube Calculator #include <iostream> using namespace std; void calculate_cube (int num) { num = num * num * num; } int main() { int num = 5; calculate_cube(num); cout << "Cube is " << num << endl; return 1; }
  • 4. Cube Calculator • What will the output of this program be? • We create a variable • We pass that variable to our function • We make that variable equal the cube of itself. • It seems like the answer should be 125… • … but it won’t be. • Why?
  • 5. Functions and Variables • We have spoken about functions in an earlier lecture. • And how we can provide information to functions by passing parameters. • When we do this, what we pass into the function is a copy of the data we have. • So we really have two versions of the same data in the program at any one time.
  • 6. Functions and Variables • In our calculate_cube function, we are working with a copy of num. • We are never directly manipulating the value of num itself. • This is known as passing by value. • We pass the value of a variable, not the variable itself. • Every variable in C++ is stored in the computer’s memory. • Sometimes we want to be able to get to that memory location. • We want to pass things by reference.
  • 7. Pointers • Here is where the pointer enters our discussion. • It points to a memory location. • Pointers come with two new syntax elements to learn. • & which is the reference operator • * which is the dereference operator. • We use these to swap between the memory location and the value of a memory location.
  • 8. Reference Operator • The & symbol is our reference operator. • You can think of it as meaning ‘the address of’ • We can use this to say ‘I want to send a memory location into this function’: int main() { int num = 5; calculate_cube(&num); cout << "Cube is " << num << endl; return 1; }
  • 9. Dereference Operator • * is the dereference operator • Think of it as ‘the value of’ • We also use this to indicate that a variable is going to be a pointer. • When we accept the parameter we are given, we want to be able to indicate we are working with a pointer. • We need to change our function a little to accommodate that:
  • 10. Our Program With Pointers #include <iostream> using namespace std; void calculate_cube (int *num) { *num = *num * *num * *num; } int main() { int num = 5; calculate_cube(&num); cout << "Cube is " << num << endl; return 1; }
  • 11. How Do They Work? • Every variable takes up a certain amount of memory. • This varies from type to type. • Each variable has a memory address. • That’s how the computer knows where to find it in memory. • A pointer is a location in memory that contains the memory address of another location. • This is known as indirection.
  • 12. Alternative Syntax #include <iostream> using namespace std; void calculate_square (int &num) { num = num * num; } int main() { int num = 5; int num2 = 10; calculate_square (num2); cout << "Square is " << num2 << endl; return 1; }
  • 13. Do We Want Them? • Yes and no. • They are invaluable for doing certain things. • They are overly complex for many requirements. • Far better method in most cases to avoid the use of pointers and make use of return values. • This is not possible in all situations. • When in doubt, try to think of a way to avoid using a pointer.
  • 14. Why Use Pointers? • Very efficient. • Copying values, especially things like objects, is very costly. • More on this in a later lecture. • Permits functions that return more than one value. • Canonical example of this is a function that swaps the contents of two variables. • Resolves some issues of data persistance. • Introduces others along the way…
  • 15. Why Not Use Pointers? • Additional complexity of code. • Code that uses pointers is almost always more complex. • Easy to make mistakes. • Pointers let you work with the live ammo of memory addresses. • You can easily manipulate the memory location rather than the memory contents. • Permits unintended side effects. • Largely negates the issue of scope.
  • 16. Alas… • Sometimes, we have to use pointers. • Because C++ is built around the assumption we will be. • We’ll see them used relatively freely when we talk about objects in a couple of weeks. • For various reasons, passing by value is not really appropriate for dealing with objects.
  • 17. Pointer Notation • When we want to represent pointers in diagram form, we use the notation below. • This is a simple representation. • We don’t worry about memory locations • Just the relationship between variables. *ptr Var
  • 18. Pointers Example 1 int main() { int *yPtr, *zPtr; int y, z; y = 10; z = 5; zPtr = &z; yPtr = &y; cout << "Y is " << y << endl; cout << "yPtr is " << yPtr<< endl; cout << "Z is " << z<< endl; cout << "zPtr is " << zPtr<< endl; return 1; }
  • 19. Pointers Example 2 int main() { int *yPtr, *zPtr; int y, z; y = 10; z = 5; zPtr = &z; yPtr = &y; cout << "Y is " << &y << endl; cout << "yPtr is " << *yPtr<< endl; cout << "Z is " << &z << endl; cout << "zPtr is " << *zPtr<< endl; return 1; }
  • 20. Pointers Example 3 int main() { int *yPtr, *zPtr; int y, z; y = 10; z = 5; zPtr = &z; yPtr = zPtr; *zPtr = 20; cout << "yPtr is " << *yPtr<< endl; cout << "zPtr is " << *zPtr<< endl; return 1; }
  • 21. When Working With Pointers • Always be clear of the relationship between variables. • Draw diagrams if needed • Always be sure of where your pointers are actually pointing. • Remember, the * means ‘the value of my current memory location’ • Be wary of side effects • Very easy to introduce!
  • 22. Summary • C++ has pointers. • Don’t sweat it too much just now… • They are extremely powerful • They let you do things you couldn’t really otherwise do. • They are extremely dangerous. • It’s very easy to lose control of your program by using them. • Be wary!