pointers and references

27
06/24/22 C++ for Java Programmers 1 Pointers and References Timothy Budd

Upload: glynis

Post on 14-Feb-2016

41 views

Category:

Documents


0 download

DESCRIPTION

Pointers and References. Timothy Budd. Pointers . Powerful Objected-Oriented mechanisms are possible due to the indirection provided through the use of pointer values. Often it is said that Java has no pointers, actually, everything is represented internally by pointer values. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Pointers and References

04/22/23 C++ for Java Programmers 1

Pointers and References

Timothy Budd

Page 2: Pointers and References

04/22/23 C++ for Java Programmers 2

Pointers Powerful Objected-Oriented mechanisms

are possible due to the indirection provided through the use of pointer values.

Often it is said that Java has no pointers, actually, everything is represented internally by pointer values.

In C++, the use of pointers is explicit and must be directly manipulated in code.

Page 3: Pointers and References

04/22/23 C++ for Java Programmers 3

Java Pointersclass box { // Java box

public int value;}

box a = new box();a.value = 7; // set variable a

box b;b = a;

Because internally reference the same value, changes to either a or b will be reflected in the other variable.

Page 4: Pointers and References

04/22/23 C++ for Java Programmers 4

a

a

b

new box()

new box()

Page 5: Pointers and References

04/22/23 C++ for Java Programmers 5

Pointers on Pointers Pointers is simply a variable that maintain as a

value the address of another location in memory. The reasons for using pointer values

A single pointer variable must reference a variety of different values over the course of execution.

A pointer will reference only a single value, but the particular value it will reference cannot be known at run time.

The amount of memory necessary to hold a value cannot be determined at compile time, and must be allocated a run-time.

Page 6: Pointers and References

04/22/23 C++ for Java Programmers 6

Pointers on Pointers

p *p

Page 7: Pointers and References

04/22/23 C++ for Java Programmers 7

Null Pointer A null pointer is a value that does not

reference any other memory location. A null pointer is analogous to an

uninitialized variable in Java. A pointer can be tested for equality to the

value zero to determine whether it is a null pointer.

Page 8: Pointers and References

04/22/23 C++ for Java Programmers 8

4 Principal Mechanisms Can be explicitly dereferenced using the unary * operator. If

p is a variable holding a pointer to a value, then *p is the value addressed by the pointer.

A pointer to a structure, or class, can combine pointer dereferencing and member field extraction using the pointer operator. p x is the same as (*p).x

Can be subscripted. Useful only if the pointer addresses an array of objects. The index is used to determine the element accessed by the expression.

An integer value can be added to or subtracted from a pointer in order to yield a new pointer. Assumed that the pointer references an array of values.

Page 9: Pointers and References

04/22/23 C++ for Java Programmers 9

The Address-of Operator The address-of operator converts a name into a pointer.

int i; // location for final valueint *p; // pointer variablep = & i; // set p to point to i

scanf("%d", p); // scan number into i

Address-of operator can be applied directly in arguments.int i; // location for final value

scanf("%d", &i); // scan number into i

Page 10: Pointers and References

04/22/23 C++ for Java Programmers 10

Pointers to Simple Values Two major operations when a pointer is referencing a

primitives Pointer vale to another pointer To dereference the pointer value

int i = 7;int j = 11;int *p = & i; // set p to point to i

*p = *p + 3; // i now has the value 10

Pointers should be compared only for equality.

Page 11: Pointers and References

04/22/23 C++ for Java Programmers 11

Pointers on Simple Values Difference between modifying a pointer

value and modifying the value that a pointer refers to.

p = & j; // change p to point to j

Page 12: Pointers and References

04/22/23 C++ for Java Programmers 12

Referencing a deleted value Nothing prevents a pointer from referencing a deleted value.

int * p; // global pointer variable

void Set () {int i; // local variablei = 7; // give i a valuep = & i; // set p to point to it}

void Use () {double d;d = 3.0;d += *p; // use the value p points to}

Page 13: Pointers and References

04/22/23 C++ for Java Programmers 13

Pointers to Pointer A pointer to a value that is itself a pointer is

declared using multiple levels of * symbols.

int main (int argc, char ** argv) {...cout << "name of program " << **argv << '\n';return 0;}

Page 14: Pointers and References

04/22/23 C++ for Java Programmers 14

Pointers and const Modifier const indicates whether it is the pointer

itself or the value it points to that is constant.

int i = 7;

const int * p = &i; // pointer to a constantint * const q = &i; // constant pointer

*p = 8; // not allowed, p points to a const*q = 8; // allowed, q is pointing to non const p = q; // allowed, p itself is not constant q = p; // not allowed q is constant

Page 15: Pointers and References

04/22/23 C++ for Java Programmers 15

void * Pointers A void pointer can reference any type of value.

double d;double * dp = & d;

void * p = dp;

A void * parameter must always be cast before it can be used.

double * dp2;dp2 = (double *) p; // convert p back into pointer to double

Page 16: Pointers and References

04/22/23 C++ for Java Programmers 16

Pointers to Functions A function pointer can be invoked

without the deference operator.double fdiv (int i, int j) { return i / (double) j; }

double (*fptr) (int, int); // declare variable fptrfptr = & fdiv; // assign value

double x = fptr(7, 14); // call ftpr directlydouble x = (*fptr) (7, 14); // dereference ftpr and call

Page 17: Pointers and References

04/22/23 C++ for Java Programmers 17

Pointers to Functionsdouble values[100];

int comp (void * a, void * b) {

double * d1 = (double *) a;double * d2 = (double *) b;return (*d1) < (*d2);

}

qsort (values, 100, sizeof(double), &comp);

Avoid qsort in code; use the STL routines instead.

Page 18: Pointers and References

04/22/23 C++ for Java Programmers 18

Pointers to Structure The arrow operator is a combination of

dereferencing and field access.struct link {int value; link * next; // pointer to next link in chain};

link finalElement; // declare a single default elementlink * firstLink = & finalElement; // set pointer to initially refer to this

(*firstLink).value = 7; // these two statementsfirstLink->value = 7; // have the same effect

Page 19: Pointers and References

04/22/23 C++ for Java Programmers 19

Pointers to Structure

for (link * p = aList; p != &finalElement; p = p->next)

cout << *p << " ";

Page 20: Pointers and References

04/22/23 C++ for Java Programmers 20

Pointers to Arrays Pointers can be subscripted just like arrays.

int values[100];

int * p = values; // legal, as values is converted into a pointer

p[4] = 7; // references same value as values[4]

Neither pointer not array index values are checked to ensure they are in range.

p[310] = 7; // index value too largep[-4] = 12; // index value too small

Page 21: Pointers and References

04/22/23 C++ for Java Programmers 21

Pointer Arithmetic It is legal to perform arithmetic on pointers.

char * text = " ... some text ";

// p++ advances pointer to next locationfor (char * p = text; *p != '\0'; p++) if (isVowel(*p))

cout << "vowel value is " << *p << "\n";

Page 22: Pointers and References

04/22/23 C++ for Java Programmers 22

Reference A reference is an alias, an alternative way to

name an existing object. Difference between reference and pointers

A reference can never be null; it must always refer to a legitimate object.

Once established, a reference can never be changed to make it point to a different object.

A reference does not require any explicit mechanism to dereference the memory address and access the actual data value.

Page 23: Pointers and References

04/22/23 C++ for Java Programmers 23

References A reference is declared by using the ampersand.

int i = 7;int & j = i; // j is an alias for ij++; // i is now 8i += 3; // i is now 11, as is j

A reference can be target of an assignment. Some functions will return a reference as a result for precisely this reason.

int values[100];int & index(int i) { return values[i + 2]; }index(27) = 12; // changes values[29];

Page 24: Pointers and References

04/22/23 C++ for Java Programmers 24

Pass by Reference Parameters The most common use of reference is in parameter

passing. A reference parameter is an alias for the corresponding actual argument value.void passTest (int & i) {i++;i = 7;}

int main ( ) { {int j = 5;passTest(j);cout << j << '\n';return 0;}

Page 25: Pointers and References

04/22/23 C++ for Java Programmers 25

Pass by Reference Parameters None of the parameter passing options in C++

matches the Java semantics.static void passTest (box i){i.value++;i = new box(7);}

public static void main (String [ ] args) {box j = new box(5);passTest(j);System.out.println("J is " + j.value);}

Page 26: Pointers and References

04/22/23 C++ for Java Programmers 26

References as Results References can also be used as a result type for a

function. 2 reasons for doing so:

A reference can be used as the target of an assignment. Therefore, a function call that returns a reference can be used on the left side of an assignment.

Returning a reference is more efficient than returning a value. Therefore, large values can be returned by reference.

Page 27: Pointers and References

04/22/23 C++ for Java Programmers 27

Example of Reference as Resultclass string { …..char & operator [ ] (unsigned int index){ return buffer[index]; } ……private:char * buffer;};

string text = "name:";text[0] = 'f'; // change name to fame

double & min (double data[ ], int n) {double minVal = data[0];for (int i = 1; i < n; i++)if (data[i] < minVal)minVal = data; return minVal; // error, reference to local}