Upload
madison-pearl-richards
View
227
Download
3
Embed Size (px)
Citation preview
[S. Uludag]
CIS / CSC 175 Problem Solving and Programming I
Winter 2010
Suleyman Uludag Department of Computer Science, Engineering and Physics (CSEP)
University of Michigan - Flint
Email: [email protected] Phone: (810) 762-3175 Fax : (810) 766-6780
April 11, 2010
Slide Set #6
Pointers
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 2
Pointers
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 3
Slide Topics
Declaring and using pointersPointer operators ( & and * )Pass-by-reference with pointersUsing const with pointersSelection sort with pointerssizeof operatorPointer arithmeticArray and pointer relationship
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 4
Introduction to PointersOne of the most powerful features of the C++ programming
Initially subtle to appreciate its beauty And difficult to master
Pointers enable1. Pass by reference2. Create and manipulate
dynamic data structures
Pointers have close relationship with arrays and strings
Value Address
a 5 1000
b 4 1004
c 34 1008
1012aPtr 1000
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 5
Declaring, Initializing and Using Pointers
Pointer variables contain memory addresses as values
Normally, variable contains specific value (direct reference)
7count
7count countPtr
Pointers contain address of variable that has a specific value (indirect reference)
CPUs efficiently reference memory via pointersIndirection (dereferencing)
Referencing value through pointer
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 6
Pointer Declaration
countPtr is a pointer to an integercount is an integer, * doesn’t apply to it
type *name;
int *countPtr, count;
Ex 1:
xPtr and yPtr are both pointers to double values.
double *xPtr, *yPtr;
Ex 2:
(* indicates variable is a pointer)
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 7
Remarks on Pointers I
Pointer initializationInitialized to 0, NULL, or an address
0 or NULL points to nothing (null pointer)
Assuming that the * used to declare a pointer distributes to all variable names in a declaration’s comma-separated list of variables can lead to errors. Each pointer must be declared with the * prefixed to the name (either with or without a space in between—the compiler ignores the space). Declaring only one variable per declaration helps avoid these types of errors and improves program readability.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 8
Remarks on Pointers II
Although it is not a requirement, including the letters Ptr in pointer variable names makes it clear that these variables are pointers and that they must be handled appropriately.Initialize pointers to prevent pointing to unknown or uninitialized areas of memory.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 9
Pointer OperatorsAddress operator (&)
Returns memory address of its operandExample
int y = 5;int *yPtr;yPtr = &y;
5y yPtr
assigns the address of variable y to pointer variable yPtrVariable yPtr “points to” yyPtr indirectly references variable y’s value
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 10
Pointer Operators II* operator (indirection or dereferencing operator)
Returns synonym for the object its operand points to*yPtr returns y (because yPtr points to y)Dereferenced pointer is an lvalue (used on the left of an assignment statement)
*yPtr = 9;
* and & are inverses of each otherWill “cancel one another out” when applied consecutively in either order
5y
40000
yPtrmemory location
40000memory location
42180
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 11
More Remarks on PointersDereferencing a pointer that has not been properly initialized or that has not been assigned to point to a specific location in memory could cause a fatal execution-time error, or it could accidentally modify important data and allow the program to run to completion, possibly with incorrect results.An attempt to dereference a variable that is not a pointer is a compilation error.Dereferencing a null pointer is normally a fatal execution-time error.The format in which a pointer is output is compiler dependent. Some systems output pointer values as hexadecimal integers, while others use decimal integers.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 12
Ex 1: Operators & and *
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 13
Output Ex 1: Operators & and *
Output
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 14
Operator precedence and associativity.
Operators Associativity Type
() [] left to right highest
++ -- static_cast< type >( operand ) left to right unary (postfix)
++ -- + - ! & * right to left unary (prefix)
* / % left to right multiplicative
+ - left to right additive
<< >> left to right insertion/extraction
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
, left to right comma
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 15
Passing Arguments to Functions by reference with Pointers
Three ways to pass arguments to a functionPass-by-valuePass-by-reference with reference argumentsPass-by-reference with pointer arguments
A function can return only one valueArguments passed to a function using reference arguments
Function can modify original values of arguments
More than one value “returned”
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 16
Pass-by-reference with pointer arguments
Simulates pass-by-referenceUse pointers and indirection operator
Pass address of argument using & operatorArrays not passed with & because array name is already a pointer* operator used as alias/nickname for variable inside of function
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 17
Ex 2: Pass-by-reference with pointer
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 18
Output Ex 2: Pass-by-reference with pointer
Output
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 19
Using const with Pointersconst qualifier
Indicates that value of variable should not be modifiedconst used when function does not need to change the variable’s value
Principle of least privilegedAward function enough access to accomplish task, but no moreA function that prints the elements of an array, takes array and int indicating length
Array contents are not changed – should be constArray length is not changed – should be const
Conclusion: If a value does not (or should not) change in the body of a function to which it is passed, the parameter should be declared const to ensure that it is not accidentally modified.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 20
Passing pointers to functions
Four ways to pass pointers to function1. Nonconstant pointer to nonconstant data2. Nonconstant pointer to constant data3. Constant pointer to nonconstant data4. Constant pointer to constant data
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 21
1.Nonconstant pointer to nonconstant data
Highest amount of accessData can be modified through the dereferenced pointerPointer can be modified to point to other data
Pointer arithmeticOperator ++ moves array pointer to the next element
Its declaration does not include const qualifier
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 22
Ex3: 1.Nonconstant pointer and nonconstant data
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 23
Output Ex3: 1.Nonconstant pointer and data
Output
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 24
2. Nonconstant pointer to constant data
Pointer can be modified to point to any appropriate data itemData cannot be modified through this pointerProvides the performance of pass-by-reference and the protection of pass-by-valueRule of thumb: If they do not need to be modified by the called function, pass large objects using pointers to constant data or references to constant data, to obtain the performance benefits of pass-by-reference.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 25
Ex4: Nonconstant pointer / constant data
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 26
Output Ex4: Nonconstant pointer / constant data
Output
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 27
Ex5: Nonconstant pointer / constant data
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 28
3. Constant pointer to nonconstant data
Always points to the same memory locationCan only access other elements using subscript notation
Data can be modified through the pointerDefault for an array name
Can be used by a function to receive an array argument
Must be initialized when declared
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 29
Ex6: Constant pointer/ nonconstant data
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 30
4. Constant pointer to constant data
Least amount of accessAlways points to the same memory locationData cannot be modified using this pointer
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 31
Ex7: Constant pointer / constant data
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 32
Ex 8: Selection Sort with pointers I
Cont’d
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 33
Ex 8: Selection Sort with pointers - II
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 34
Output Ex 8: Selection Sort w/pointers
Output
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 35
sizeof operator
sizeof operatorReturns size of operand in bytesFor arrays, sizeof returns
( size of 1 element ) * ( number of elements )
If sizeof( int ) returns 4 then int myArray[ 10 ]; cout << sizeof( myArray );
will print 40Can be used with
Variable namesType namesConstant values
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 36
Ex 9: sizeof operator
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 37
Output
Output: Ex 9: sizeof operator
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 38
Ex 10: Determining data type size
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 39
Output
Output: Ex 10: Determining data type size
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 40
more on sizeof operator IPerformed at compile-timeFor double realArray[ 22 ];
Use sizeof realArray / sizeof( double ) to calculate the number of elements in realArray
Parentheses are only required if the operand is a type nameThe number of bytes used to store a particular data type may vary between systems. When writing programs that depend on data type sizes, and that will run on several computer systems, use sizeof to determine the number of bytes used to store the data types.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 41
more on sizeof operator II
Omitting the parentheses in a sizeof operation when the operand is a type name is a compilation error.Because sizeof is a compile-time unary operator, not an execution-time operator, using sizeof does not negatively impact execution performance.To avoid errors associated with omitting the parentheses around the operand of operator sizeof, many programmers include parentheses around every sizeof operand.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 42
Pointer Arithmetic Increment/decrement pointer (++ or --)Add/subtract an integer to/from a pointer (+ or +=, - or -=)Pointers may be subtracted from each otherPointer arithmetic is meaningless unless performed on a pointer to an arrayMost computers today have two-byte or four-byte integers. Some of the newer machines use eight-byte integers. Because the results of pointer arithmetic depend on the size of the objects a pointer points to, pointer arithmetic is machine dependent.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 43
Pointer Arithmetic Example
int v[5];Memory Address
v[0] 1000
v[1] 1004
v[2] 1008
v[3] 1010
v[4] 1012
vPtrint *vPtr = &v[0];
int *vPtr = v;
same ptr assignment can be done with the
following:
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 44
Pointer Arithmetic Example (contd.)vPtr += 2;
// 1000+2*4=1008
Memory Address
v[0] 1000
v[1] 1004
v[2] 1008
v[3] 1010
v[4] 1012
vPtr
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 45
Pointer Arithmetic Example (contd.)
vPtr--;Memory Address
v[0] 1000
v[1] 1004
v[2] 1008
v[3] 1010
v[4] 1012
vPtr
Note: Postincrement or preincrement and postdecrement or predecrement are identical here.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 46
Remarks on pointer arithmetic
Using pointer arithmetic on a pointer that does not refer to an array of values is a logic error.Subtracting or comparing two pointers that do not refer to elements of the same array is a logic error.Using pointer arithmetic to increment or decrement a pointer such that the pointer refers to an element past the end of the array or before the beginning of the array is normally a logic error.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 47
Pointer assignment
Pointer can be assigned to another pointer if both are of same type
If not same type, cast operator must be usedException
Pointer to void (type void *)Generic pointer, represents any typeNo casting needed to convert pointer to void *Casting is needed to convert void * to any other typevoid pointers cannot be dereferenced
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 48
Pointer comparison
Use equality and relational operatorsCompare addresses stored in pointers
Comparisons are meaningless unless pointers point to members of the same array
ExampleCould show that one pointer points to higher-index element of array than another pointer
Commonly used to determine whether pointer is 0 (null pointer)
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 49
Pointer – Array RelationshipArrays and pointers are closely related
Array name is a constant pointerPointers can do array subscripting operations
Accessing array elements with pointersAssume declarations:
Element b[ n ] can be accessed by *( bPtr + n )Called pointer/offset notation
Addresses&b[ 3 ] is same as bPtr + 3
Array name can be treated as pointerb[ 3 ] is same as *( b + 3 )
Pointers can be subscripted (pointer/subscript notation)
bPtr[ 3 ] is same as b[ 3 ]
int b[ 5 ];int *bPtr; bPtr = b;
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 50
Tips on array-pointer relationship
Although array names are pointers to the beginning of the array and pointers can be modified in arithmetic expressions, array names cannot be modified in arithmetic expressions, because array names are constant pointers. For clarity, use array notation instead of pointer notation when manipulating arrays.
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 51
Ex 11: array and pointers
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 52
Output Ex 11: array and pointersOutpu
t
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 53
Ex 12: string copying w/ arrays and pointers I
Cont’d
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 54
Ex 12: string copying w/ arrays and pointers II
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 55
Output Ex 12: string copying w/ arrays and pointers
Output
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 56
Ex 13: zero out an array with pointers
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 57
Output Ex 13: zero out an array
Output
[S. Uludag]U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 58
Remarks on precedenceThe pointer indirection (*) and increment (++) have the same level of precedence but they associate right-to-left.Therefore,
*p++ = 0
is evaluated as *(p++) = 0, which means that pointer is incremented by one but only after using its value in the operation.
[S. Uludag]
Commands (keywords) of slides #6
U. of Michigan-Flint, Dept. of CSEP CIS/CSC 175 Problem Solving and Programming I 59