SlideShare una empresa de Scribd logo
1 de 22
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!

Más contenido relacionado

La actualidad más candente

Functions in c++
Functions in c++Functions in c++
Functions in c++Maaz Hasan
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Lecture 4: Functions
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: FunctionsVivek Bhargav
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascriptrelay12
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use casesSrajan Mor
 
Function class in c++
Function class in c++Function class in c++
Function class in c++Kumar
 
Data weave 2.0 advanced (recursion, pattern matching)
Data weave 2.0   advanced (recursion, pattern matching)Data weave 2.0   advanced (recursion, pattern matching)
Data weave 2.0 advanced (recursion, pattern matching)ManjuKumara GH
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++Vraj Patel
 
Inline function(oops)
Inline function(oops)Inline function(oops)
Inline function(oops)Jay Patel
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Philip Schwarz
 

La actualidad más candente (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Lecture 4: Functions
Lecture 4: FunctionsLecture 4: Functions
Lecture 4: Functions
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Monad Fact #6
Monad Fact #6Monad Fact #6
Monad Fact #6
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Data weave 2.0 advanced (recursion, pattern matching)
Data weave 2.0   advanced (recursion, pattern matching)Data weave 2.0   advanced (recursion, pattern matching)
Data weave 2.0 advanced (recursion, pattern matching)
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Inline functions
Inline functionsInline functions
Inline functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Inline function(oops)
Inline function(oops)Inline function(oops)
Inline function(oops)
 
CPP04 - Selection
CPP04 - SelectionCPP04 - Selection
CPP04 - Selection
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Refactoring
RefactoringRefactoring
Refactoring
 
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
Refactoring: A First Example - Martin Fowler’s First Example of Refactoring, ...
 

Similar a CPP08 - Pointers

Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxDeepasCSE
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxsangeeta borde
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
Lecture 1 Introduction C++
Lecture 1 Introduction C++Lecture 1 Introduction C++
Lecture 1 Introduction C++Ajay Khatri
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handlingRai University
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptchintuyadav19
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 

Similar a CPP08 - Pointers (20)

CPP06 - Functions
CPP06 - FunctionsCPP06 - Functions
CPP06 - Functions
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Pointers
PointersPointers
Pointers
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Lecture 1 Introduction C++
Lecture 1 Introduction C++Lecture 1 Introduction C++
Lecture 1 Introduction C++
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
C language
C languageC language
C language
 

Más de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 

Más de Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Último

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Último (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

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!