Chapter 6 (B) - Arrays and Pointer (Part 2 - Pointers)
Chapter 6 (B) - Arrays and Pointer (Part 2 - Pointers)
Chapter 6(b) -
Arrays and Pointers Variables that store the memory address
of other variables
- Pointers Variable name is prefixed by a ‘ * ’
(dereference operator)
Pointer’s data type must match the data
type of the variable it points to
Can be assigned the address of another
variable using the ‘&’(address of operator)
1 2
5 6
Example 5
#include <iostream> Example 5 Expected Output
using namespace std;
int main ()
{
The value of num is 5
int num = 5; The value of num after num = 10 is 10
int* iPtr = #
The value of num after *iPtr = 15 is 15
cout << "The value of num is " << num << endl;
num = 10;
cout << "The value of num after num = 10 is " <<
num << endl;
*iPtr = 15;
cout << "The value of num after *iPtr = 15 is "
<< num << endl;
} 15 16
The first change should be familiar, by the direct The placement of the dereferencing
assignment of a value to num: operator before a pointer is said to
num = 10. dereference the pointer.
However, the second change is accomplished a Some texts refer to the indirection operator
new way, using the indirection operator:
as the dereferencing operator
*iPtr = 15;
The value of a de-referenced pointer is not
The dereferencing operator is an asterisk, the
same asterisk that you used to declare the an address, but rather the value at that
pointer or to perform multiplication address—that is, the value of the variable
that the pointer points to.
17 18
String are: One Two Three Four Passing a pointer to the original value of a
String are: First Two Three Last function allow the called function to
operate on the original value
21 22
Example 7
Example 7 Expected Output
num value is 5
num value is now 15
23 24
Example 8: Pointers to Pointers Example 8 Expected Output
int main()
{
n = 44
int n=44; &n = 0x0064fd78
cout << " n = " << n << endl;
cout << " &n = " << &n << endl; pn = 0x0064fd78
int* pn=&n; // pn holds the address of n
cout << " pn = " << pn << endl;
&pn = 0x0064fd7c
cout << " &pn = " << &pn << endl; *pn = 44
cout << " *pn = " << *pn << endl;
int** ppn=&pn; // ppn holds the address of pn ppn = 0x0064fd7c
cout << " ppn = " << ppn << endl;
cout << " &ppn = " << &ppn << endl; &ppn = 0x0064fd80
cout << " *ppn = " << *ppn << endl; *ppn = 0x0064fd78
cout << "**ppn = " << **ppn << endl;
} **ppn = 44
25 26