Tải bản đầy đủ (.ppt) (18 trang)

C++ lecture 17

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (226.08 KB, 18 trang )

C++ Programming
Lecture 17

Pointers
– Part
II
The Hashemite
University
Computer Engineering
Department
(Adapted from the textbook slides)


Outline








Introduction.
The Relationship Between Pointers and
Arrays.
Pointer Expressions and Pointer Arithmetic.
sizeof Operator for Arrays and Pointers.
Functions call by reference using pointers.
Examples.

The Hashemite University



2


The Relationship Between
Pointers and Arrays I


Arrays and pointers are closely related






Array name is a constant pointer that contains the
address of the first element in the array (you cant
move this pointer to points to another element of
the array).
Pointers can do array subscripting operations
Having declared an array b[ 5 ] and a pointer bPtr
You have two ways to make bPtr points to the
first element of the array
1 -

bPtr is equal to b
bptr == b

2 - bptr is equal to the address of the first element of b
bptr == &b[ 0 ]

The Hashemite University

3


The Relationship Between
Pointers and Arrays II


Accessing array elements with pointers


Element b[ n ] can be accessed by *( bPtr + n )




Array itself can use pointer arithmetic.





Called pointer/offset notation
b[ 3 ] same as *(b + 3)
Note : *(b+3) is correct, while *(b+=3) is not
correct because you try to move this pointer to
another location

Pointers can be subscripted (pointer/subscript

notation)


bPtr[ 3 ] same as b[ 3 ]
The Hashemite University

4


Example --Array name is pointer
to first element
char t[5]={'a','b','c','d','e'};
cout<< *t<*t=‘w';
cout<
"<<*t; // will print w w

The Hashemite University

5


Pointer to Char and Strings


Character array:
char color[] = "blue";

Creates 5 element char array, color, (last element is

'\0'), the same effect of:
char color[] = {‘b’, ‘l’, ‘u’, ‘e’, ‘\0’};




variable of type char *
char *colorPtr = "blue";
cout<< *colorPtr; // will print b
cout<< colorPtr; // will print blue


Creates a pointer to string “blue”, colorPtr, and
stores it somewhere in memory
The Hashemite University

6


Pointer Expressions and
Pointer Arithmetic I


Pointer arithmetic









Increment/decrement pointer (++ or --)
Add/subtract an integer to/from a pointer( + or += , - or
-=)
Pointers
may be subtracted from each other
 
Pointer arithmetic is meaningless unless performed on an
array

5 element int array on a machine using 4 byte
location
ints
3000
3004
3008
3012
3016


vPtr points to first element v[ 0 ], which is at location
v[0]
v[1]
v[2]
v[3]
3000





vPtr = 3000

vPtr += 2; sets vPtr to 3008


v[4]

vPtr points to v[ 2 ]

pointer variable vPtr

The Hashemite University

7


Example
address
es
double array[5]

293
8

294
6

2.3 -5


295
4

-1

296
2

297
0

3.3 4.9

double *pointer = &array; //  pointer = 2938 points to
array[0]
pointer++; //  pointer = 2946 points to array[1]
pointer+=2//  pointer = 2962 points to array[3]
The Hashemite University

8


Pointer Expressions and
Pointer Arithmetic II


Subtracting pointers


Returns the number of elements between two addresses

vPtr2 = &v[ 2 ];
vPtr = &v[ 0 ];
vPtr2 - vPtr = 2



Pointer comparison


Test which pointer points to the higher numbered array
element
Using the above pointers
if(vptr > vptr2)



Test if a pointer points to 0 (NULL)
if ( vPtr == NULL )
statement
The Hashemite University

9


sizeof Operator and
Arrays


sizeof






Returns size of operand in bytes
Returns the result of type size_t which is unsigned
integer.
For arrays, sizeof returns
( the size of 1 element ) * ( number of elements )



if sizeof( int ) = 4, then
int myArray[10];
cout << sizeof(myArray);

will print 40
 To get the size of an array (number of elements) using
sizeof operator do the following:
Array size = sizeof(myArray)/ sizeof(int);
The Hashemite University

10


sizeof Operator and
Pointers


Applying sizeof operator for a pointer always returns a

result of 4 regardless of the data type to which the
pointer is pointing.
char x;
char *p=&x;
double y=0;
double *ypt=&y;
cout<cout<points)
cout<cout<points)
The Hashemite University

11


Calling Functions by
Reference


Call by reference with pointer arguments






Pass address of argument using & operator
Allows you to change actual location in memory

Arrays are not passed with & because the array name is
already a pointer contains the address of the first element of
the array in the memory.
* operator used as alias/nickname for variable inside of
function
void doubleNum( int *number )
{
*number = 2 * ( *number );
}




*number used as nickname for the variable passed in
When the function is called, must be passed an address
doubleNum( &myNum );
The Hashemite University

12


1
2
3
4
5
6
7
8
9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

// Fig. 5.7: fig05_07.cpp
// Cube a variable using call-by-reference
// with a pointer argument
#include <iostream>
using std::cout;
using std::endl;
void cubeByReference( int * );

//

Notice how the address of
number is given cubeByReference expects a
prototype
pointer (an address of a variable).


int main()
{
int number = 5;

}

cout << "The original value of number is " << number;
cubeByReference( &number );
cout << "\nThe new value of number is " << number << endl;
return 0;
Inside cubeByReference,

void cubeByReference( int *nPtr )
{
*nPtr = *nPtr * *nPtr * *nPtr;
}

*nPtr is used (*nPtr is
number).
// cube number in main

The original value of number is 5
The new value of number is 125

The Hashemite University

13



Example I
// Converting lowercase letters to uppercase letters
// using a non-constant pointer to non-constant data.
#include <iostream.h>
#include <cctype> // prototypes for islower and toupper
void convertToUppercase( char * );
int main()
{
char phrase[] = "characters and $32.98";
cout << "The phrase before conversion is: " << phrase;
convertToUppercase( phrase );
cout << "\nThe phrase after conversion is: “ << phrase <<
endl;
return 0;
} // end main

The Hashemite University

14


Example I … cont.
// convert string to uppercase letters
void convertToUppercase( char *sPtr )
{
while ( *sPtr != '\0' ) { // current character is not '\0'
if ( islower( *sPtr ) ) // if character is lowercase,
*sPtr = toupper( *sPtr ); // convert to uppercase
++sPtr; // move sPtr to next character in string
} // end while

} // end function convertToUppercase

The Hashemite University

15


Example II
// Copying a string using array notation and pointer notation.
#include <iostream.h>
void copy1( char *, const char * ); // prototype
void copy2( char *, const char * ); // prototype
int main()
{
char string1[ 10 ];
char *string2 = "Hello";
char string3[ 10 ];
char string4[] = "Good Bye";
copy1( string1, string2 );
cout << "string1 = " << string1 << endl;
copy2( string3, string4 );
cout << "string3 = " << string3 << endl;
return 0; // indicates successful termination
} // end main

The Hashemite University

16



Example II … cont.
// copy s2 to s1 using array notation
void copy1( char *s1, const char *s2 )
{
for ( int i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ )
; // do nothing in body
} // end function copy1
// copy s2 to s1 using pointer notation
void copy2( char *s1, const char *s2 )
{
for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ )
; // do nothing in body
} // end function copy2
The Hashemite University

17


Additional Notes


This lecture covers the following material from the textbook:


Chapter 5: Sections 5.6 – 5.8

The Hashemite University

18




Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×