• No results found

12-Pointers.pdf

N/A
N/A
Protected

Academic year: 2020

Share "12-Pointers.pdf"

Copied!
22
0
0

Loading.... (view fulltext now)

Full text

(1)

SEQUENTIAL AND OBJECT

ORIENTED PROGRAMMING

(2)

Content

2

Pointer declaration

Pointer initialization

Pointer operators (assignment, arithmetic, equality and relational)

Arrays and pointers

Accessing elements in pointer to array

(3)

Objectives

3

By the end you should recognize:

What pointers are, how they are used and why they are needed

Declaration and initialization of pointers

Usage of address-of (&) and dereferencing (*) operators

Common operators that can be used with pointers

Differences between pointers and references

How to use pointers to pass arguments to the function by reference

Declaring and using pointer to string or array of characters

(4)

Pointer

A variable or constant that holds a memory address

You can think of pointer as a variable or constant that points to another

variable or data structure

Special variables that contain memory addresses as values

It contains the address of the memory location where the data is

(5)

Pointer Declaration

Syntax

Examples

int

*myPtr;

int

*myPtr1, *myPtr2;

int

*myPtr, var ;

int

* Ptr1, Ptr2;

5

(6)

Pointer Initialization

Can be initialized to

0

NULL [ points to nothing (null pointer) ]

an address

Examples

int

*Ptr1=0, *Ptr2=NULL ;

How can be initializes pointer to an address of another variable?

(7)

Pointer Operators

7

Address-of Operator (

&

)

Assign address of variable to a pointer

int

p =1, *ptr =

&

p;

ptr

indirectly references variable

p

’s value

Dereferencing Operator (

*

)

Returns the value of the variable a pointer points to

int

p =1, *ptr =

&

p;

cout <<

*

ptr ;

//*ptr is a synonym of p

*

ptr = 5 ;

// it is as if you wrote p=5;

1

p

(8)

8

1 // Fig. 8.4: fig08_04.cpp

2 // Using the & and * operators.

3 #include <iostream> 4 using std::cout; 5 using std::endl; 6

7 int main() 8 {

9 int a; // a is an integer

10 int *aPtr; // aPtr is an int * -- pointer to an integer

11

12 a = 7; // assigned 7 to a

13 aPtr = &a; // assign the address of a to aPtr

14

15 cout << "The address of a is " << &a

16 << "\nThe value of aPtr is " << aPtr;

17 cout << "\n\nThe value of a is " << a

18 << "\nThe value of *aPtr is " << *aPtr;

19 cout << "\n\nShowing that * and & are inverses of "

20 << "each other.\n&*aPtr = " << &*aPtr

21 << "\n*&aPtr = " << *&aPtr << endl;

22 return 0; // indicates successful termination

23 } // end main

The address of a is 0012F580 The value of aPtr is 0012F580

The value of a is 7 The value of *aPtr is 7

Showing that * and & are inverses of each other. &*aPtr = 0012F580

(9)

Precedence & Associativity of Operators

9

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

(10)

Pointer Arithmetic Operators

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 a pointer to

an array

(11)

Pointer Arithmetic Operators (cont.)

5 element

int

array on a machine using 4 byte

int

s

vPtr

points to first element

v[ 0 ]

, at location 3000

vPtr = &v[ 0 ];

vPtr += 2;

sets

vPtr

to 3008 (3000 + 2 * 4)

vPtr

points to

v[ 2 ]

(12)

Pointer Arithmetic Operators (cont.)

Subtracting pointers

Returns number of elements between two addresses

vPtr2 = &v[ 2 ];

vPtr = &v[ 0 ];

vPtr2 - vPtr

is 2

Pointer assignment

Pointer can be assigned to another pointer if both are of same type

If not same type, cast operator must be used

int

x, *xptr = &x;

double

y,*yptr=&y;

(13)

Pointer to void

Generic pointer, represents any type

No casting needed to convert pointer to void *

Casting is needed to convert void * to any other type

void pointers

cannot

be dereferenced

void

*wptr;

int

x=3, *xptr = &x;

Double

y=4.5, *yptr=&y;

xptr = (

int

*) yptr;

wptr = xptr;

wptr = yptr;

xptr = wptr ;

// Error

xptr = (

int

*) wptr;

cout << *xptr << *yptr ;

cout << *wptr ;

// Error

(14)

Pointer Comparison

Done by using equality and relational operators

Compare addresses stored in pointers

Comparisons are meaningless unless pointers point to members of

the same array

Could show that one pointer points to higher-index element of array than

another pointer

vPtr2 = &v[ 2 ];

vPtr = &v[ 0 ];

if

( vPtr2 > vPtr )

cout << “vptr points to an element at a higher index”;

Commonly used to determine whether pointer is 0 (null pointer)

if

( ptr == NUL ) …

(15)

Arrays and Pointers

Assume declarations

int

b[5];

int

*bPtr;

Array name

b

is a

Constant pointer

that points to the first element of the array

bPtr = b;

// will make bptr point to the 1st array element

(16)

Accessing Elements

bPtr = b;

Addresses

&

b

[

3

]

is same as

bPtr

+

3

To access the element at array index 3

b

[

3

]

[ array/

subscript

notation ]

bPtr

[

3

]

[ pointer/

subscript

notation ]

*

( bPtr + 3 ) [ pointer/

offset

notation ]

*

( b + 3 ) [ array/

offset

notation ]

16

b

bPtr

(17)

17

Outline

1 // Fig. 8.20: fig08_20.cpp

2 // Using subscripting and pointer notations with arrays.

3 #include <iostream> 4 using std::cout; 5 using std::endl; 6

7 int main() 8 {

9 int b[] = { 10, 20, 30, 40 }; // create 4-element array b

10 int *bPtr = b; // set bPtr to point to array b

11

12 // output array b using array subscript notation

13 cout << "Array b printed with:\n\nArray subscript notation\n"; 14

15 for ( int i = 0; i < 4; i++ )

16 cout << "b[" << i << "] = " << b[ i ] << '\n'; 17

18 // output array b using the array name and pointer/offset notation

19 cout << "\nPointer/offset notation where " 20 << "the pointer is the array name\n";

21

22 for ( int offset1 = 0; offset1 < 4; offset1++ )

23 cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << '\n';

Using array subscript notation

(18)

18

Outline

24

25 // output array b using bPtr and array subscript notation

26 cout << "\nPointer subscript notation\n";

27

28 for ( int j = 0; j < 4; j++ )

29 cout << "bPtr[" << j << "] = " << bPtr[ j ] << '\n'; 30

31 cout << "\nPointer/offset notation\n";

32

33 // output array b using bPtr and pointer/offset notation

34 for ( int offset2 = 0; offset2 < 4; offset2++ ) 35 cout << "*(bPtr + " << offset2 << ") = "

36 << *( bPtr + offset2 ) << '\n';

37

38 return 0; // indicates successful termination

39 } // end main

Using pointer subscript notation

(19)

Pointer-based Strings

String as arrays of Characters

char

color[] = "blue";

char

color[] = { 'b', 'l', 'u', 'e', '\0' };

String as pointer to character

char

*colorPtr = "blue";

19

‘l’

‘b’

‘u’ ‘e’ ‘\0’

colorPtr

(20)

20

1 // Fig. 8.21: fig08_21.cpp

2 // Copying a string using array notation and pointer notation.

3 #include <iostream> 4 using std::cout; 5 using std::endl; 6

7 void copy1( char *, const char * ); // prototype

8 void copy2( char *, const char * ); // prototype

9

10 int main() 11 {

12 char string1[ 10 ]; 13 char *string2 = "Hello"; 14 char string3[ 10 ];

15 char string4[] = "Good Bye"; 16

17 copy1( string1, string2 ); // copy string2 into string1

18 cout << "string1 = " << string1 << endl;

19

20 copy2( string3, string4 ); // copy string4 into string3

21 cout << "string3 = " << string3 << endl;

22 return 0; // indicates successful termination

(21)

21

Outline

24

25 // copy s2 to s1 using array notation

26 void copy1( char * s1, const char * s2 ) 27 {

28 // copying occurs in the for header

29 for ( int i = 0; ( s1[ i ] = s2[ i ] ) != '\0'; i++ ) 30 ; // do nothing in body

31 } // end function copy1

32

33 // copy s2 to s1 using pointer notation

34 void copy2( char *s1, const char *s2 ) 35 {

36 // copying occurs in the for header

37 for ( ; ( *s1 = *s2 ) != '\0'; s1++, s2++ ) 38 ; // do nothing in body

39 } // end function copy2

string1 = Hello string3 = Good Bye

Use array subscript notation to copy

string in

s2

to character array

s1

Use pointer notation to copy string

in

s2

to character array in

s1

(22)

Included Sections

22

References

Related documents

The more so do I hesitate to believe and accept the above letter because, although my sainted mother had been in America for almost fifty years, she could

The mean values of naked eye limiting magnitude reported by GLOBE at Night citizen scientists strongly correlates with both the observed values of emitted light measured by the

Emirates NBD Retail Banking &amp; Wealth Management (RBWM) division continued to outperform the market in 2014, gaining market share growth across most products and customer

Second, when evaluating the model's fit to the data, we obtain very strong evidence in favour of the DSGE model with extrapolative expectations in asset pricing over the DSGE

(2012) Relationship of sperm DNA fragmentation, apoptosis and dysfunction of mitochondrial membrane potential with semen parameters and ART outcome after intracytoplasmic

In another study, 168 middle-aged men with at least two cardiovascular risk factors who were physically inactive (physical activity &lt; 3 times per week) were divided into

The curriculum for students enrolled in a manicurist and pedicurist course shall consist of four hundred (400) clock hours of technical instruction and practical