0% found this document useful (0 votes)
9 views

4 - Pointers

The document discusses pointers in C++. A pointer stores the memory address of a variable and can be used to access or modify that variable's value. The document provides examples of declaring pointer variables and using dereferencing and reference operators to demonstrate how pointers work.

Uploaded by

Mhlengi Wiseman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

4 - Pointers

The document discusses pointers in C++. A pointer stores the memory address of a variable and can be used to access or modify that variable's value. The document provides examples of declaring pointer variables and using dereferencing and reference operators to demonstrate how pointers work.

Uploaded by

Mhlengi Wiseman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Pointers

COMP315
2024
1
2
Pointers
• A pointer is the memory address of a variable. The address “points”
to the variable because it identifies the variable by stating where the
variable is, rather than stating what the variable’s name is
Pointers be like…

3
Operators
• Referencing operator (&): The operator in front of an ordinary
variable produces the address of that variable. It produces a pointer
that points to the variable

• Dereferencing operator (*): The operator in front of a pointer variable


produces the variable it points to

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Code Example
int v = 48;
int *p = &v;
int &r = v;

cout << v << endl; // 48


cout << p << endl; //ox3afee2
cout << *p << endl; // 48
cout << r << endl; // 48
cout << &r << endl; //ox3afee2

20
Code Example – with Table
Variable Name Value Memory Address
int v = 48; v 48 ox3afee2
int *p = &v; r 48 ox3afee2
int &r = v; p ox3afee2 ox3afee3

cout << v << endl; // 48


cout << p << endl; //ox3afee2
cout << *p << endl; // 48
cout << r << endl; // 48
cout << &r << endl; //ox3afee2

21
Code Example
int v = 48;
int *p = &v;
int &r = v;
*p = 12;

cout << v << endl; // 12


cout << p << endl; //ox3afee2
cout << *p << endl; // 12
cout << r << endl; // 12
cout << &r << endl; //ox3afee2
22
Code Example – with table
int v = 48; Variable Name Value Memory Address
int *p = &v; v
48 ox3afee2
r
int &r = v;
p ox3afee2 ox3afee3
*p = 12;

cout << v << endl; // 12


cout << p << endl; //ox3afee2
cout << *p << endl; // 12
cout << r << endl; // 12
cout << &r << endl; //ox3afee2
23
Another Code Example
int x = 5;
int &y = x;

cout << x << endl; // 5


cout << y << endl; // 5
cout << &y << endl; //ox3afecdc

y=10;

cout << x << endl; // 10


cout << y << endl; // 10
cout << &y << endl; //ox3afecdc
24
25
26

You might also like