Download presentation
Presentation is loading. Please wait.
1
Pointers & Functions
2
Pointers and Functions
Functions can take pointers: C equivalent to pass by ref #include <iostream> using namespace std; //C++ style void doubleVariable(int& x) { x = x * 2; } //C style void doubleVariableCStyle(int* x) { *x = (*x) * 2; } int main() { int num = 10; cout << num << endl; doubleVariable(num); cout << num << endl; doubleVariableCStyle(&num); cout << num <<#include <iostream> using namespace std; //C++ style void doubleVariable(int& x) { x = x * 2; } //C style void doubleVariableCStyle(int* x) { *x = (*x) * 2; int main() { int num = 10; cout << num << endl; doubleVariable(num); doubleVariableCStyle(&num); return 0; endl; return 0; }
3
Passing Pointers Pointers used like reference params: p1 p2 x 5 y 4
4
Passing Pointers Pointers used like reference params: temp p1 p2 x 5 y
4
5
Passing Pointers Pointers used like reference params: temp 5 p1 p2 x 5
y 4
6
Passing Pointers Pointers used like reference params: temp 5 p1 p2 x 4
y 4
7
Passing Pointers Pointers used like reference params: temp 5 p1 p2 x 4
y 5
8
Passing Pointers Pointers used like reference params: p1 p2 x 4 y 5
9
Passing Pointers Directly passing pointers p1 p2 x 5 pt1 0x004 pt2
10
Passing Pointers Directly passing pointers – addresses copied
Can change x/y or p1/p2 Can't change pt1 / pt2 p1 0x004 p2 0x008 x 5 pt1 0x004 pt2 0x008 y 4
11
Passing Pointers Passing references to pointers p1 p2 x 5 pt1 0x004
y 4
12
Passing Pointers References to pointers
temp References to pointers Can change the pointers themselves p1 p2 x 5 pt1 0x004 pt2 0x008 y 4
13
Passing Pointers References to pointers
temp 0x004 References to pointers Can change the pointers themselves p1 p2 x 5 pt1 0x004 pt2 0x008 y 4
14
Passing Pointers References to pointers
temp 0x004 References to pointers Can change the pointers themselves p1 p2 x 5 pt1 0x008 pt2 0x008 y 4
15
Passing Pointers References to pointers
temp 0x004 References to pointers Can change the pointers themselves p1 p2 x 5 pt1 0x008 pt2 0x004 y 4
16
Passing Pointers References to pointers
Can change the pointers themselves p1 p2 x 5 pt1 0x008 pt2 0x004 y 4
17
Return Pointers Can return a pointer from a function:
18
Returning Pointers Can return pointer – better not be to local variable
19
Returning Pointers Can return pointer – better not be to local variable x 10 pt
20
Returning Pointers Can return pointer – better not be to local variable x 10 pt 0x110 p 0x110
21
Returning Pointers Can return pointer – better not be to local variable p 0x110
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.