copyright 2001 oxford consulting, ltd1 january 2001 - 1 - pointers and more pointers pointers and...
Post on 22-Dec-2015
228 Views
Preview:
TRANSCRIPT
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 1 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
We’ve now looked at
Pointers
Arrays
Strings
Let’s now see how all these tie together
Also look at advanced pointer concepts
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 2 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Let’s begin with look at the relationship between pointers and
arrays
Recall that an array is collection of values of a single data type
a[n-1]a[0] a[2]a[1]
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 3 -
Pointers and More PointersPointers and More Pointers
Pointers and ArraysConsider an array of ints, a [ ], stored in memory
By definition, the value of a variable of type array
Is the address of the 0th element
For our array, the following are equivalent
&a [ 0 ]
a
Thus, If a [ ] is loaded at address 3000
Then
&a[0] = a = 3000
3000
3020
3040
3060
3180
a[0]
a[1]
a[2]
a[3]
a[9]
3000
3020
3040
3060
3180
a[0]
a[1]
a[2]
a[3]
a[9]
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 4 -
Pointers and More PointersPointers and More Pointers
Pointers and ArraysSuch an equivalence allows us to write
A bit more surprising is
a [ j ]
is equivalent to
*(a + j)
Should not be….let’s see why
int a[10]; // declare an array of 10 ints
int *pa; // declare a pointer to an int
pa = a; // assign the address of a[ ] to the pointer
int a[10]; // declare an array of 10 ints
int *pa; // declare a pointer to an int
pa = a; // assign the address of a[ ] to the pointer
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 5 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
We know
a + j is the address of the jth element beyond a
We have also seen
a [ j ] = a + j * sizeof (an element of a)We have several ways of addressing an array
int a[ ] = {1, 2, 3, 4, 5};
int *pa = a;
a[ i ]
*(pa + i)
*pa++
(*pa)++ // which increments the contents
We have several ways of addressing an array
int a[ ] = {1, 2, 3, 4, 5};
int *pa = a;
a[ i ]
*(pa + i)
*pa++
(*pa)++ // which increments the contents
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 6 -
Pointers and More PointersPointers and More Pointers
Pointers and ArraysMulti Dimensional Arrays
We’ve been looking at arrays in one dimension
It’s Possible to declare multiple dimensional arrays
Our arrays have had one column and multiple rows
We can extend these by simply adding more columns
It all reduces to managing pointers
We’ll start with 2 dimensions
Then briefly explore larger arrays
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 7 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Multi Dimensional ArraysLet’s go back to the basics
We know an array is collection of values
Single data type is represented as
Then stored in memory as
a[n-1]a[0] a[2]a[1]a[n-1]a[0] a[2]a[1]
3000
3020
3040
3060
3180
a[0]
a[1]
a[2]
a[3]
a[9]
3000
3020
3040
3060
3180
a[0]
a[1]
a[2]
a[3]
a[9]
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 8 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Multi Dimensional Arrays
Array can be specified such that the elements are objects of any
type including pointers or addresses
If a single dimensional array contains pointers to other arrays, we
can easily build up a two dimensional array
We specify array by its number of
Rows
Columns
An array’s dimension refers to the number of columns
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 9 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional Arrays
The simplest complex array is two dimensional
Its elements are one dimensional arrayssyntax:
type arrayName [ rowSize ] [ columnSize ]syntax:
type arrayName [ rowSize ] [ columnSize ]
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 10 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional ArraysWe can write
int year [12][31]
The declaration says that year is
Array of 12 elements
Which we can use to express the months
Array of 31 ints
Which we can use to express the days of the month
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 11 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional ArraysFor two dimensional array, we can access a
particular
element by specifying the row and column
To
To get the 7th month and 13th day…..
….We write year[7][13]
As expected…..
First index identifies the row
Second index specifies column in that row
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 12 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional Array ImplementationTwo dimensional arrays are implemented as
an array of
pointers to arrays
b[m][n]
They are stored as an array of m pointers to arrays with n
elements each
Elements of each constituent array are stored in adjacent
memory locations
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 13 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional Array Implementation
3000
3020
3040
3060
3180
a0[n]
a1[n]
a2[n]
a3[n]
an-1[n]
3000
3020
3040
3060
3180
a0[n]
a1[n]
a2[n]
a3[n]
an-1[n]
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 14 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional Array ImplementationTwo dimensional array differ from simple array of pointers
to
arrays The declaration of two dimensional array
Initializes the main array to point to component arrays
All component arrays are same size
Array of pointers
Must be initialized by programmer
All component arrays may be different sizes
Sometimes referred to as a ragged array
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 15 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional Array ImplementationFor array a[2] [3], the elements stored as
a[0][0], a[0][1], a[0][2], a[1[0], a[1[1], a[1][2]
Element a[1][2] is addressed as:*(*(a + 1) + 2)
1. a is 2 by 3 array. It points to first element of a 3 element subarray
2. a + 1 points to the second 3 element subarray
3. *(a + 1) points to the first element of the second 3 element subarray
4. *(a + 1) + 2 points to the third element of the second subarray
5. *(*(a + 1) + 2) is third element in second subarray
1. a is 2 by 3 array. It points to first element of a 3 element subarray
2. a + 1 points to the second 3 element subarray
3. *(a + 1) points to the first element of the second 3 element subarray
4. *(a + 1) + 2 points to the third element of the second subarray
5. *(*(a + 1) + 2) is third element in second subarray
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 16 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Two Dimensional Array Implementation
3000
3020
3040
3060
3180
a0[0,1,2]
a1[0,1,2]
a
a+1
*(a+1) *(a+1) + 2
3000
3020
3040
3060
3180
a0[0,1,2]
a1[0,1,2]
a
a+1
*(a+1) *(a+1) + 2
In general a two-dimensional arrays are accessed by Array notation or Pointer notation
Array notation is used when dealing with the array
itself and Pointer notation is used when all you have is the
address of the array
The address of any element in our example array is guaranteed to be
(a + 3*i + j)
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 17 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Dynamic Allocation of Two Dimensional ArraysTwo-dimensional arrays can be allocated on
the heap with
the new operator with following syntax:
The allocation defines x as a pointer to
i arrays of j elements
int (* x)[j] = new int[i][j];int (* x)[j] = new int[i][j];
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 18 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Deleting Two Dimensional ArraysWhen dynamically allocated two-dimensional
arrays are
deleted…..
….The delete operator requires only one [ ] regardless of the number of dimensions in the array
delete [] x; // Correct.
delete [][] x; // Error. Use only one []
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 19 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Multidimensional Dimensional Arrays
C and C++ place no restriction on the number of dimensions
an array may have
Multidimensional arrays are stored in row major order
Elements differing only in last subscript are stored adjacently
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 20 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Multidimensional Dimensional ArraysPointer conversion and addressing done as
in two
dimensional arrays only in more dimensions
In General an expression of form….
i by j by k
….is converted to the form
pointer to j by k
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 21 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Multidimensional Dimensional ArraysThe mechanics of the two-dimensional arrays
can be
extended to cover arrays with more dimensions...
For following 3 dimensional array
int a[2][3][4];
The address of an element (&a[i][j][k])
Is guaranteed to be (array + 2*3*i + 3*j + k)
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 22 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Generic and Null Pointers
The pointers we’ve dealt with point to a variable of a
particular type
Often we would like to use same pointer to point to a variable
of any data type
In C++ will see this is a simple form of polymorphism
ANSI C++ introduces the generic pointer
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 23 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Generic PointersThe generic pointer is a pointer to type void
void *
void * pointer guaranteed to be large enough to hold pointer
to any type of object except a function type
Such a pointer can be converted to type void * and back
again with no loss of information
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 24 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Generic PointersA generic pointer cannot be dereferenced with these
operators*
[ ] subscript
On many machines all pointers are the same size
However to ensure max portability because of potentially
different sizes
void * pointer must converted back to pointer of
appropriate type before dereferencing
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 25 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Dereferencing Generic Pointers
void * myGenericPtr;
int myValue = 3;
myGenericPtr = &myValue;
int tempValue = *myGenericPtr; // illegal
void * myGenericPtr;
int myValue = 3;
myGenericPtr = &myValue;
int tempValue = *myGenericPtr; // illegal
int a = 9;
int *intPtr = &a; // point to a
cout << *intPtr << endl; // prints 9
void* genPtr = static_cast<void*>(&a); // preferred C++ style cast
int* intPtr2 = static_cast<int*>(genPtr); // preferred C++ style cast
cout << *intPtr2 << endl; // prints 9
int a = 9;
int *intPtr = &a; // point to a
cout << *intPtr << endl; // prints 9
void* genPtr = static_cast<void*>(&a); // preferred C++ style cast
int* intPtr2 = static_cast<int*>(genPtr); // preferred C++ style cast
cout << *intPtr2 << endl; // prints 9
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 26 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Null PointersDereferencing a pointer with
No assigned value gives undetermined results
A value of 0 is Illegal
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 27 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Null Pointers When declared, local pointers contain whatever values
were in memory at time….
….. dereferencing treats that value as an address
Global and Static Pointers are initialized to 0…..
…..dereferencing usually gives runtime error and program termination
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 28 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Null PointersANSI C++ offers solution and defines a special
pointer
null pointer
Its value points to no object or function
(void *) 0
Special macro NULL defined in header file <stddef>
Definition depends upon compiler and operating system
Often defined as NULL ((void *) 0 )
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 29 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Function Pointers
The pointers we’ve discussed so far have been pointers to
data
We can also define pointers to functions or function pointerssyntax
return type (* functionPointer) (<arg0, arg1...argn>)
arg list may be empty
syntax
return type (* functionPointer) (<arg0, arg1...argn>)
arg list may be empty
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 30 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Function Pointers
int (* intFunctPtr) ();
Read as
intFunctPtr is A pointer to a functionTaking no argsReturning an int
int (* intFunctPtr) ();
Read as
intFunctPtr is A pointer to a functionTaking no argsReturning an int
double (* doubleFunctPtr) (int, char);
Read as
doubleFunctPtr is A pointer to a functionTaking two args: an int and a charReturning a double
double (* doubleFunctPtr) (int, char);
Read as
doubleFunctPtr is A pointer to a functionTaking two args: an int and a charReturning a double
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 31 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Function PointersHow do we obtain a pointer to function….
….There are several ways Use address of operator, & Use function name with no parameter list
int (* intFunctPtr) ();
int myFunction();
intFunctPtr = &myFunction;
or
intFunctPtr = myFunction;
int (* intFunctPtr) ();
int myFunction();
intFunctPtr = &myFunction;
or
intFunctPtr = myFunction;
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 32 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Dereferencing Function PointersWe can also dereference a function pointer
in several ways
(* functPtr)( argument-list)
functPtr(argument-list)
double (*doubleFunctPtr)(int, char);
double yourFunction (int, char)
doubleFunctPtr = yourFunction;
(*doubleFunctPtr)(3, ‘b’);
double (*doubleFunctPtr)(int, char);
double yourFunction (int, char)
doubleFunctPtr = yourFunction;
(*doubleFunctPtr)(3, ‘b’);
int (* intFunctPtr) ();
int myFunction();
intFunctPtr = myFunction;
(*intFunctPtr)();
int (* intFunctPtr) ();
int myFunction();
intFunctPtr = myFunction;
(*intFunctPtr)();
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 33 -
Pointers and More PointersPointers and More Pointers
Pointers and ArraysFunction Pointers
Function and Data pointers may have significantly different
representations Based upon machine architecture Byte Ordering Alignment requirements Sizes Memory models
Conversion between function and data pointers in ANSI C++
Has undefined behavior
Conversion to or from type void * in ANSI C++
No guarantee of safety
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 34 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Indirect ReferenceIn addition to address of a variable a pointer
variable can
contain the address of another pointer
….We have pointer to pointer
To retrieve the value we must apply dereference operator
twicesyntax
type ** pointerName
syntax
type ** pointerName
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 35 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Indirect ReferenceLet’s declare an integer
int myInt = 3
A pointer to an int
int* myIntPrt = &myInt;
…and a pointer to that pointer
int** myIntPtrPtr = &myIntPtr;
Let
myInt be stored at memory address 4000
myIntPtrPtr be stored at address 3000
myIntPtr be stored at address 3020
3000
3020
3040
3060
3 0 2 0
myIntPtrPtr
4000 0 0 0 3
myInt
4 0 0 0myIntPtr
3000
3020
3040
3060
3 0 2 0
myIntPtrPtr
4000 0 0 0 3
myInt
4 0 0 0myIntPtr
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 36 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Indirect Reference Thus the expression
int myValue = ** myIntPtrPtr
Assigns the value 3 to the variable myValue
Since myIntPtrPtr is pointing to
1. Memory location 3020
2. Which points to memory location 4000
3. Which contains the value 0003
Since myIntPtrPtr is pointing to
1. Memory location 3020
2. Which points to memory location 4000
3. Which contains the value 0003
3000
3020
3040
3060
3 0 2 0
myIntPtrPtr
4000 0 0 0 3
myInt
4 0 0 0myIntPtr
myValue 0 0 0 3
3000
3020
3040
3060
3 0 2 0
myIntPtrPtr
4000 0 0 0 3
myInt
4 0 0 0myIntPtr
myValue 0 0 0 3
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 37 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Indirect Reference
Similarly
int myValue = 4;
**myIntPtrPtr = myValue;
Places the value 4 into memory location 4000
3000
3020
3040
3060
3 0 2 0
myIntPtrPtr
4000 0 0 0 4
myInt
4 0 0 0myIntPtr
myValue 0 0 0 4
3000
3020
3040
3060
3 0 2 0
myIntPtrPtr
4000 0 0 0 4
myInt
4 0 0 0myIntPtr
myValue 0 0 0 4
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 38 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Reference Types
C++ introduces an additional way of referring to an object
Called reference
A reference serves as an alias or alternate name for an object
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 39 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Reference TypesRules for references
A reference
Must be initialized when created like a const
A pointer initialized any time
Once initialized to an object it cannot be changed to
refer to another object
A pointer can be pointed to different object anytime
syntax
type & varName = aValue
syntax
type & varName = aValue
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 40 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Reference TypesCannot
Have NULL reference
Point to reference
Have an array of references
Take the address of a reference
Compare references
Assign to them
Do arithmetic on them
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 41 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Initialization of Reference TypesA non const - only initialized to lvalue of exact type
lvalue is value that can appear on left hand side of an assignment statement
unsigned char mine;
int d1, d2;
int &a = 1024; // illegal - not lvalue
char &b = mine; // illegal - not exact type
int &c = d1 + d2; // illegal - not lvalue
unsigned char mine;
int d1, d2;
int &a = 1024; // illegal - not lvalue
char &b = mine; // illegal - not exact type
int &c = d1 + d2; // illegal - not lvalue
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 42 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
Initialization of Reference Typesconst - can have an rvalue that is an lvalue not of the
exact typervalue can only appear on right hand side of an assignment statement
unsigned char mine;
int d1, d2;
const int = 1024; // legal
const char &b = mine; // legal
const int &c = d1 + d2; // legal
unsigned char mine;
int d1, d2;
const int = 1024; // legal
const char &b = mine; // legal
const int &c = d1 + d2; // legal
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 43 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
References vs. Pointers
Do not support pointer like declarations
Cannot have arrays of references
Reference to arrays
We can’t declare an array of references…..
int& v[ ]; // array of references to ints
….because
v[i] *(v + i) // pointer to a reference
We can’t declare an array of references…..
int& v[ ]; // array of references to ints
….because
v[i] *(v + i) // pointer to a reference
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 44 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
References as ParametersReferences can be used as parameters in a function
callPass by value...
Function never accesses the actual arguments
Manipulates local copy stored on the stack
Changes made to local copies not always suitable
Large objects passed args must be modified
Pass by value...
Function never accesses the actual arguments
Manipulates local copy stored on the stack
Changes made to local copies not always suitable
Large objects passed args must be modified
Pass by reference….
Function accesses actual arguments
Address of args is passed
If we don’t want arg to be changed
Use const specifier
Pass by reference….
Function accesses actual arguments
Address of args is passed
If we don’t want arg to be changed
Use const specifier
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 45 -
Pointers and More PointersPointers and More Pointers
Pointers and Arrays
References as Parameters
void incrementR (int &number);
void incrementV (int number);
int main(void){ int number = 10; int number1 = 20;
incrementR(number); cout << number << endl; // Will print 11
incrementV (number1); cout << number1 << endl; // Will print 20
return 0;}
void incrementR (int &number);
void incrementV (int number);
int main(void){ int number = 10; int number1 = 20;
incrementR(number); cout << number << endl; // Will print 11
incrementV (number1); cout << number1 << endl; // Will print 20
return 0;}
void incrementR (int &aNumber){
aNumber++; // Passed by reference}
void incrementV (int aNumber){
aNumber++; // Passed by value}
void incrementR (int &aNumber){
aNumber++; // Passed by reference}
void incrementV (int aNumber){
aNumber++; // Passed by value}
top related