2-OOP 2016-spr CH10
2-OOP 2016-spr CH10
Chapter 10
Instructor: Sungahn Ko
2016 Spring CSE24101
10.1 Pointers and the Address Operator
Each variable in a program is stored at a unique
address in memory
Use address operator & to get address of a
variable:
int num = -23;
cout << # // prints address in hexadecimal
// 0x4a00 in the example below
Address
num 0x4a00 -23
2
10.2 Pointer Variables
Pointer variable (pointer):
variable that holds Figure from wikipedia.org
an address
a: pointer variable
b: another variable
Pointers provide an
alternate way to access
memory locations.
3
Define a Pointer Variable
Definition:
int *intptr;
Read as:
“intptr can hold the address of an int” or
“the variable that intptr points to has type int” or
“intptr is a pointer to int”
Spacing in definition does not matter
int * intptr;
int* intptr;
4
Pointer Variables
Assignment:
int num = 25; The address of num may vary at
int *intptr; every execution, since the memory
intptr = # will be re-allocated whenever the
code is executed.
Memory layout: num intptr
25 0x4a00
address of num: 0x4a00
4 7 11
starting address of vals: 0x4a00
6
Arrays and Pointers
Array name can be used with indirection operator
int vals[] = {4, 7, 11};
cout << *vals; // displays 4, 1st element
7
Pointers in Expressions
We have
int vals[]={4,7,11};
int *valptr = vals;
Q: What is (valptr + 1)?
= (address in valptr) + (1 * size of an int)
cout << *(valptr+1); // displays 7
cout << *(valptr+2); // displays 11
Cout << valptr[2]; // displays 11
Must use ( ) in expression
8
Array Access Methods
Array elements can be accessed in many ways
The following 4 methods are all identical
int vals[3];
int *valptr = vals;
Array access method Example
array name and [ ] vals[2] = 11;
pointer to array and [ ] valptr[2] = 11;
array name and subscript
*(vals+2) = 11;
arithmetic
pointer to array and
*(valptr+2) = 11;
subscript arithmetic
9
Array Access
Array notation
vals[i]
is equivalent to the pointer notation
*(vals + i)
10
10.4 Pointer Arithmetic
Some arithmetic operators can be used with
pointers:
Increment and decrement operators ++, --
Integers can be added to or subtracted from pointers
using the operators +, -, +=, and -=
One pointer can be subtracted from another by using
the subtraction operator -
11
Pointer Arithmetic
Assume the variable definitions as
int vals[]={4,7,11};
int *valptr = vals;
Examples for ++ and --
valptr++; // points at 7
valptr--; // now points at 4
Example for adding an integer to a pointer:
cout << *(valptr + 2);
// will print 11
12
Pointer Arithmetic
Assume the variable definitions as
int vals[]={4,7,11};
int *valptr = vals;
Example for +=:
valptr += 2; // points at 11
Example of pointer subtraction
cout << valptr - vals;
This statement prints 2: the number of ints
from vals to valptr
13
10.5 Initializing Pointers
Can initialize to addresses of other variables
int num, *numPtr = #
// int *numPtr; *numPtr = # (X)
// int *numPtr; numPtr = # (O)
int val[ISIZE], *valptr = val;
Initial value must have correct type
float cost;
int *ptr = &cost; // won't work
Can initialize to NULL or 0 (zero)
int *ptr = NULL;
14
10.6 Comparing Pointers
Relational operators can be used to compare
addresses in pointers
> < == != >= <=
Comparing addresses in pointers is not the same
as comparing contents pointed at by pointers:
if (ptr1 == ptr2) // compares addresses
if (*ptr1 == *ptr2) // compares contents
15
10.7 Pointers as Function Parameters
A pointer can be used as a function parameter
16
Pointers as Function Parameters
Typical format
1) In prototype and heading – use * on parameter
void getNum(int *ptr);
2) In body – use * to dereference the pointer
cin >> *ptr;
3) In function call – use address argument to the
function
getNum(&num);
17
Pointer vs. Reference variable
Pointer Reference variable
void swap( void swap(
int *x, int *y) int &x, int &y)
{ {
int temp; int temp;
temp = *x; temp = x;
*x = *y; x = y;
*y = temp; y = temp;
} }
18
Meaning
Use of ★ and &
int *x
Variable x is a pointer to an integer variable
*x
Dereference of x (to the variable)
function(int &y)
Variable y is an alias of function argument (reference
variable)
&y
Address of variable y
19
10.9 Dynamic Memory Allocation
Allocate memory when defining a variable
double dvalue;
int iarray[100];
20
Create a Variable
Memory for a variable is allocated while program
is running
Needs a pointer variable to store memory location
“new” operator is used to allocate memory
double *dptr;
dptr = new double;
21
Create an Array
Can also use new to allocate array
double *arrayPtr;
arrayPtr = new double[25];
22
Releasing Dynamic Memory
Use delete to free dynamic memory
delete dptr;
Use delete [] to free dynamic array memory
delete [] arrayptr;
23
Dangling Pointers and Memory Leaks
A memory leak occurs if no-longer-needed dynamic
memory is not freed
This memory is unavailable for reuse within the program
Solution: free up dynamic memory after use
24
10.10 Returning Pointers from
Functions
Pointer can be return type of function
int* newNum();
Function must not return a pointer to a local
variable in the function
The memory for local variables is automatically deleted
when the function returns, and thus will not exist.
Function should only return a pointer
to data that was passed to the function as an argument
to dynamically allocated memory
25
char *getName()
{
char name[81];
cout << “Enter name: “;
cin.getline(name,81); char *getName()
return name;
{
}
// what is wrong here? char *name;
name = new char[81];
char *getName(char *name) cout << “Enter name: “;
{ cin.getline(name,81);
cout << “Enter name: “; return name;
cin.getline(name,81); }
return name; // acceptable:
} // return dynamic memory
// acceptable:
// return memory passed-over
26
10.11 Pointers to Class Objects and
Structures
Can create pointers to objects and structure
variables
struct Student {…};
class Square {…};
Student stu1;
Student *stuPtr = &stu1;
Square sq1[4];
Square *squarePtr = &sq1[0];
Need () when using * and .
(*stuPtr).studentID = 12204;
27
Structure Pointer Operator
Simpler notation than (*ptr).member
Use the form ptr->member:
stuPtr->studentID = 12204;
squarePtr->setSide(14);
28
Dynamic Memory with Objects
Can allocate dynamic structure variables and
objects using pointers:
stuPtr = new Student;
Can pass values to constructor:
squarePtr = new Square(17);
delete causes destructor to be invoked:
delete squarePtr;
29
10.12 Selecting Members of Objects
Situation: A structure/object contains a pointer as
a member. There is also a pointer to the
structure/ object.
Problem: How do we access the pointer member
via the structure/object pointer?
struct GradeList
{
string courseNum;
int * grades;
}
GradeList test1, *testPtr = &test1;
30
Selecting Members of Objects
Expression Meaning
testPtr->grades Access the grades pointer in
test1. This is the same as
(*testPtr).grades
*testPtr->grades Access the value pointed at by
testPtr->grades. This is the
same as *(*testPtr).grades
*test1.grades Access the value pointed at by
test1.grades
31
Q&A
32
Checkpoints
10.5 Rewrite the following loop so it uses pointer
notation instead of subscript notation
for (int x=0; x<100; x++)
count << array[x] << endl;
cout << *(array + x) << endl;
34
Example Program 10-14
double * sales, for(int c=0; c<numDays, c++)
total = 0.0, total += sales[c];
average;
int numDays; average = total/numDays;
35
Program 10-6
size of an int = 4 bytes
36
Program 10-11
number
10
20 doubleValue(&number) val
0x2902 5
0x2902
parameter in
double function
doubleValue(int * val)
{
*val *= 2;
}
37
Pointer vs. Reference variable
Pointer Reference variable
void swap( void swap(
int *x, int *y) int &x, int &y)
{ {
int temp; int temp;
temp = *x; temp = x;
*x = *y; x = y;
*y = temp; y = temp;
} }
38
Pointers to Constant
39
Pointer to Constant – What does the
Definition Mean?
40
Constant Pointers
Defined with const keyword adjacent to variable
name:
int classSize = 24;
int * const classPtr = &classSize;
Must be initialized when defined
Can be used without initialization as a function
parameter
Initialized by argument when function is called
Function can receive different arguments on different
calls
While the address in the pointer cannot change, the
data at that address may be changed
41
Constant Pointer – What does the
Definition Mean?
42