0. pointers in c++
TRANSCRIPT
-
7/24/2019 0. Pointers in C++
1/103
Pointers and DynamicMemory
-
7/24/2019 0. Pointers in C++
2/103
Memory Management
Memory managementArrays
Dynamic memoryDynamic arrays and pointersBuilding a vector class
-
7/24/2019 0. Pointers in C++
3/103
Memory Management
-
7/24/2019 0. Pointers in C++
4/103
Memory Requirements
codestorage
datastorage
-
7/24/2019 0. Pointers in C++
5/103
Memory Management
When a program runs memory hasto be allocated for its processes and
its variablesThat is, working memory, or RAM
There needs to be a system foreciently allocating such memory We will !ust consider how memory is
allocated to program data "variables#
-
7/24/2019 0. Pointers in C++
6/103
RAM
We can consider Random AccessMemory "RAM# as a long se$uence of
bytes %tarting with &
'nding with the amount of main memory"()#
RAM is addressable and supportsrandom accessThat is, we can go to byte *,++,-)*
without having to visit all the preceding
-
7/24/2019 0. Pointers in C++
7/103
RAM Illustrated
& ) * + . / - 0
0 )&-+-.)1)/ )&-+-.)1)- )&-+-.)1)1 )&-+-.)1)2 )&-+-.)1*& )&-+-.)1*) )&-+-.)1** )&-+-.)1*+
3) 4B 5 ),&-+,-.),1*. bytes
6onsider a computer with )4B3of RAM
This is a fairly abstractillustration "so ignores a
variety of issues#
-
7/24/2019 0. Pointers in C++
8/103
Goals
As much as possible we would like tosatisfy three goals when allocating
memoryTime eciencyThat is, we should be able to $uickly 7nd
sucient memory to store a variable%pace eciency We don8t want to waste memory
9ow overhead
We don8t want a large amount of
-
7/24/2019 0. Pointers in C++
9/103
Stack Memory
There is a very simple way oforgani:ing memory that meets these
goals Assign memory locations to variables in
se$uence With no gaps
;nce a variable is no longer re$uiredrelease the memory, allowing it to beover(written
We will call this organi:ation the
-
7/24/2019 0. Pointers in C++
10/103
Stack Memory SimpleExample
9et8s look at a simple e/-=
?otice that this e/-
-
7/24/2019 0. Pointers in C++
11/103
Stack and Functions
9et8s look at a more comple).)= double s$Cr 5s$uare"radius#= return s$Cr 3 pi=
double s$uare"double
-
7/24/2019 0. Pointers in C++
14/103
Anoter Example
int main"# int r 5 += double area 5circleArea"r#=
double circleArea"doubleradius# double pi 5 +>).)= double s$Cr 5s$uare"radius#= return s$Cr 3 pi=
double s$uare"double
-
7/24/2019 0. Pointers in C++
15/103
Stack Memory
n stack memory variables for afunction are allocated the ne
-
7/24/2019 0. Pointers in C++
16/103
Re!erence Parameters
%ome functions have referenceparameters
There are two common reasons fordoing this'ciency int sum(const vector & v)
%ums the contents of the vectorAnd because we want the changes
made to the variable to persist after
the function
-
7/24/2019 0. Pointers in C++
17/103
Stack Pro"lems
There is one big issue with stackmemory
Because memory is allocated inse$uence it is not possible to change thebyte si:e of a variable
%trings and vectors fre$uently
change si:e t is more correct to say that a string
variable may refer to strings of diFerent
si:es
-
7/24/2019 0. Pointers in C++
18/103
#anging a $ector%s Si&e
int main"# vector GintHvec"+#= vI&J 5 )= vI)J 5 *= vI*J 5 += double vid 5*>+2-=
insertCnesi:e"# L)#=
main memory
vec vid3
) * + *>+2-
3very importantdouble
-
7/24/2019 0. Pointers in C++
19/103
#anging a $ector%s Si&e
int main"# vector GintHvec"+#= vI&J 5 )= vI)J 5 *= vI*J 5 += double vid 5*>+2-=
insertCnesi:e"# L)#=
main memory
vec v3vid3
* +
3v is a referenceto vec, itactually contains the byte
address of vec
*>+2-
3very importantdouble
+n
oi
.)
This is a problem,we8ve !ust corruptedthe 7rst . bytes ofvid
-
7/24/2019 0. Pointers in C++
20/103
'ypes (! Memory
t turns out you can divide memoryinto three broad categories
%tatic Automatic
DynamicThese types of memory are typically
used for diFerent sorts of programdata Although 6LL gives programmers
choice over which type of memory to
-
7/24/2019 0. Pointers in C++
21/103
datastoragestatic
Storage
codestorage
automatic
dynamic
-
7/24/2019 0. Pointers in C++
22/103
Static Storage
%tatically stored variables last for thelifetime of a program
The number of static variables doesnot change as a program runs %o no special system is re$uired to
maintain them%tatic storage is used for global
constants And other things 0
-
7/24/2019 0. Pointers in C++
23/103
Automatic Storage
Eunction variables and parametersuse automatic storage by default
Automatic variables are typicallymanaged on a stack as we havebeen discussingThe stack is an allocated area of
memory that grows and shrinks asfunctions are called
Memory is allocated se$uentially
"without gaps#
-
7/24/2019 0. Pointers in C++
24/103
Functions and Memory
A variable de7ned in a function blockonly persists for the lifetime of that
function call nless it is declared as static
6onsider what memory might beallocated when a function is running Memory re$uired for the functionNs data
and only re$uired during the functioncall
Memory that is to persist beyond the8
-
7/24/2019 0. Pointers in C++
25/103
ArraysA Digression Erom Memory
-
7/24/2019 0. Pointers in C++
26/103
Arrays
Before looking at dynamic memorylet8s look at a basic data structure O
the array Arrays are used to store multiple values
of the same type, much as vectors do
'
-
7/24/2019 0. Pointers in C++
27/103
)at Is An Array*
An array variable is a collection ofother variablesQou can think of an array as something
that contains variablesThis is important because an integer
array is notan integer, it is a collectionof integers
The items stored in an array"elements# are stored se$uentially inmain memory
ust like variables on the stack
-
7/24/2019 0. Pointers in C++
28/103
Declaring Arrays
An array is declared with a type, and[]s to indicate that the variable is an
arrayThe type declares the type of the array
elements
intmyArray[10]
type of thedata stored in
the array
brackets declarethat the variable is
an array
si:e of thearray
name of thearray
-
7/24/2019 0. Pointers in C++
29/103
Array Indexing
The elements of the array areaccessed using an inde
This does nothappen with
other pass(by(value
-
7/24/2019 0. Pointers in C++
49/103
)at%s an Array*
To understand what is going on inthe previous e
-
7/24/2019 0. Pointers in C++
50/103
More A"out Arrays
An array is a se$uence of bytes inmain memory reserved for the array
contents e>g> int arr[10]; Reserves .& contiguous bytes
An intis . bytes, . 3 )& 5 .&
'ach element can be referenced usinginde
-
7/24/2019 0. Pointers in C++
51/103
More A"out Indexing
6onsider this assignment statementV arr[] = 63;
To 7nd this array element 9ook up the address stored in arr Multiply type si:e ". for an int# by the
indee>
-
7/24/2019 0. Pointers in C++
66/103
'e si&eo! (perator
The sizeofoperator allows us to 7ndout the si:e of a type or variable
cout GG si:eof"int#= cout GG si:eof"YcN#= ZZsi:e of a char
cout GG si:eof"6ylinder#= ZZthe si:e of a6ylinder
sizeofreturns a number of bytes
-
7/24/2019 0. Pointers in C++
67/103
Re!erence (perator
The K operator is also used to createreference parameters
Where a variable is passed to a functionby reference, rather than by value
Reference parameters are notpointersA reference parameter is given the
address of the argument passed tothe function And thereafter behaves like a normal
variable
-
7/24/2019 0. Pointers in C++
68/103
(4erloaded (perators
6LL tends to re(use operators The meaning can be determined by the conte
-
7/24/2019 0. Pointers in C++
69/103
Pointers andAssignment
int = 16;inty = 77;int5'1 = :; //assi.n '1 the address o(
int5'6 = :y;//assi.n '6 the address o( y
p)
p*
)
*--
arr"i-e;int5 arr = newint[arr"i-e];
The variable is apointer, used tostore an address
6reates thisarray in dynamic
memoryData created in dynamicmemory persists until theapplication is terminated,regardless of which
function it was created in
+sing D namic Arra s
-
7/24/2019 0. Pointers in C++
83/103
+sing Dynamic Arrays
;nce a dynamic array has beencreated it can be used like any otherarray ndividual array elements are accessed
using an indeoperator can be used to referto an ob!ect8s methods using apointer "tudent5 ' = new "tudent)9101;
'>addFrade)3, 3C33;The >operator is onlyused with
pointers t should not be used with regular ob!ect
variables
se dot notation for such variables
Deletion
-
7/24/2019 0. Pointers in C++
98/103
Deletion
%tack "non dynamic# memory isreleased automatically When a function 7nishes e
-
7/24/2019 0. Pointers in C++
99/103
Deleting Memory
The keyword delete is used to freedynamically allocated memory
When deleting a dynamic arraydelete must be followed by IJs
Memory space that has beendeallocated cannot be freed again
Attempting to do this results in an error
delete (perator
-
7/24/2019 0. Pointers in C++
100/103
delete(perator
The delete operator is used to freememory that has been dynamicallyallocated int 5 ' = new int;
5' = 63;
CCC
delete ';'ach new should have a matching
delete
Although often not in the same function
6e5 and Delete
-
7/24/2019 0. Pointers in C++
101/103
6e5 and Delete
int' arr = )*++;
int s, = 0;
cout -- lease enter si,e;
cin s,;
arr = ne int[s,];int' ("int = ne int12;
delete ("int;
delete[] arr;
arr = )*++;delete[] arr;
delete ("int;
frees up . bytes
frees up the .& bytesallocated for the dynamic
arraysafe since arris ?99, but
pointlessresults in an
indicates that arrdoes not point to
anythingallocates space for an int
array of si:e sz, andreturns its address which is
then assigned to arr
3uilding a Simple
-
7/24/2019 0. Pointers in C++
102/103
3uilding a Simple$ector #lassBringing t All Toegether 0
3uilding a $ector #lass
-
7/24/2019 0. Pointers in C++
103/103
3uilding a $ector #lass
We will write a class that usespointers and dynamic arrays tobehave much like a vector
To keep things simple we will !ust mplement a vector of doubles rather
than a template for any type
mplement pushCback and si:e methods %tart by allowing access to the vector
elements using get"inde