0% found this document useful (0 votes)
50 views42 pages

2-OOP 2016-spr CH10

This document discusses pointers in C++. It defines pointers as variables that hold memory addresses and can be used to indirectly access the value of the variable located at that address. Key points covered include: defining and initializing pointer variables; using pointers to access array elements; pointer arithmetic operations like increment, addition and subtraction; passing pointers as function parameters; dynamically allocating memory using new and deleting it using delete; and issues around returning pointers from functions.

Uploaded by

yjshin0920
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views42 pages

2-OOP 2016-spr CH10

This document discusses pointers in C++. It defines pointers as variables that hold memory addresses and can be used to indirectly access the value of the variable located at that address. Key points covered include: defining and initializing pointer variables; using pointers to access array elements; pointer arithmetic operations like increment, addition and subtraction; passing pointers as function parameters; dynamically allocating memory using new and deleting it using delete; and issues around returning pointers from functions.

Uploaded by

yjshin0920
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Pointers

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 << &num; // prints address in hexadecimal
// 0x4a00 in the example below
Address
num 0x4a00 -23

 The address of a memory location is called a


pointer

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 = &num; will be re-allocated whenever the
code is executed.
 Memory layout: num intptr
25 0x4a00
address of num: 0x4a00

 Can access num using intptr and indirection


operator *:
cout << intptr; // prints 0x4a00
cout << *intptr; // prints 25
cout << &num; // prints 0x4a00
cout << num; // prints 25
Variable that this pointer intptr points to
(dereferencing
5
the pointer)
10.3 Arrays and Pointers
 Array name represents the starting address of the
array, and works as if a pointer variable

int vals[] = {4, 7, 11};

4 7 11
starting address of vals: 0x4a00

cout << vals; // displays 0x4a00


cout << vals[0]; // displays 4

6
Arrays and Pointers
 Array name can be used with indirection operator
int vals[] = {4, 7, 11};
cout << *vals; // displays 4, 1st element

 Pointer can be used as an array name


int vals[] = {4, 7, 11};
int *valptr = vals;
cout << valptr[1]; // displays 7

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)

 No bounds checking – be careful

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 = &num;
//  int *numPtr; *numPtr = &num; (X)
//  int *numPtr; numPtr = &num; (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

 Works like a reference parameter (i.e., passing


by reference) to allow change to argument from
within function
 A pointer parameter must be explicitly
dereferenced to access the contents at that
address

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;
} }

int num1 = 2; int num1 = 2;


int num2 = -3; int num2 = -3;
swap(&num1, &num2); swap(num1, num2);

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];

 What if the array size is unknown at initialization?


 dynamic memory allocation

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;

 new returns the starting address of the allocated


memory.

21
Create an Array
 Can also use new to allocate array
double *arrayPtr;
arrayPtr = new double[25];

 As before, one can use [ ] or pointer arithmetic to


access the array
cin >> arrayPtr[10];

 What if there is not sufficient memory?


 Program is often forced to terminate

22
Releasing Dynamic Memory
 Use delete to free dynamic memory
delete dptr;
 Use delete [] to free dynamic array memory
delete [] arrayptr;

 Use delete only with dynamic memory!


 Error when trying to delete static array
double data[20]; // static array
delete [] data; // ERROR or warning

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

 A pointer is dangling if it contains the address of


memory that has been freed by delete
 Solution: set such dangling pointers to 0 as soon as
memory is freed
delete dptr;
dptr = NULL;

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);

in place of 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

“.” operator has a higher priority than “*” operator

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;

10.7 Assume pint is a pointer variable. Which


statement is invalid C and D are invalid. Only addition
and subtraction are valid
A) pint++; B) --pint; arithmetic operations with pointers
C) pint /= 2; D) pint *= 4;
E) pint += x; // x is an int
33
Pointers as Function Parameters
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int num1 = 2, num2 = -3;
swap(&num1, &num2);

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;

cin >> numDays; // print output


cout << total << average;
// dynamic memory allocation
sales = new double[numDays]; // Free memory
delete[] sales;
// Get inputs sales = 0;
for(int c=0; c<numDays, c++)
cin >> sales[c]; return 0;

35
Program 10-6
 size of an int = 4 bytes

numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]

*numbers *(numbers+1) *(numbers+2)*(numbers+3) *(numbers+4)

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;
} }

int num1 = 2; int num1 = 2;


int num2 = -3; int num2 = -3;
swap(&num1, &num2); swap(num1, num2);

38
Pointers to Constant

 Must use const keyword in pointer definition:


const double taxRates[] =
{0.65, 0.8, 0.75};
const double *ratePtr;

 Use const keyword for pointers in function


headers to protect data from modification
from within function

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

You might also like