6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Pointers CSE 2451 Rong Shi.
Ch 7. Operator Overloading Timothy Budd. Ch 7. Operator Overloading2 Introduction Almost all operators in C++ can be overloaded with new meanings. Operators.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers Class #9 – Pointers Pointers Pointers are among C++ ’ s most powerful, yet most difficult concepts to master. We ’ ve seen how we can use references.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Windows Programming Lecture 03. Pointers and Arrays.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
Motivation and Overview
Java Primer 1: Types, Classes and Operators
Student Book An Introduction
C Basics.
Java Review: Reference Types
Pointers and References
Built-In (a.k.a. Native) Types in C++
SPL – PS2 C++ Memory Handling.
Presentation transcript:

6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd

6/10/2015C++ for Java Programmers 2 Java Primitive & Reference Types Primitive types: Numeric – byte, short, long, float, double Boolean Char Reference types: String Array Class

6/10/2015C++ for Java Programmers 3 Java Primitive & Reference Types Primitive type variables contain the values of the things they represent. int x; x Reference type variables contain references to (addresses of) the objects they represent. box box b; b 27 box data

6/10/2015C++ for Java Programmers 4 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.

6/10/2015C++ for Java Programmers 5 Java Pointers class box {// Java box public int value; } box a = new box(); a.value = 7; // set variable a box b; b = a;  Because both a and b internally reference the same value, changes to either a or b will be reflected in the other variable.

6/10/2015C++ for Java Programmers 6 a a b new box()

6/10/2015C++ for Java Programmers 7 C++ Primitive & Reference Types Primitive types: Numeric – byte, short, long, float, double Boolean Char Class & Struct Reference types: Array String (simple strings implemented by arrays)

6/10/2015C++ for Java Programmers 8 Pointers on Pointers A pointer is simply a variable that holds as its 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 compile time or at the beginning of execution. The amount of memory necessary to hold a value cannot be determined at compile time, and must be allocated a run-time.

6/10/2015C++ for Java Programmers 9 Pointers on Pointers p*p

6/10/2015C++ for Java Programmers 10 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 or the constant NULL to determine whether it is a null pointer.

6/10/2015C++ for Java Programmers 11 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 ( p[5] ) 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 (p + 5) This use assumes that the pointer references an array of values.

6/10/2015C++ for Java Programmers 12 The Address-of Operator The address-of operator converts a name into a pointer. int i; // location for final value int *p; // pointer variable p = & 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 as above

6/10/2015C++ for Java Programmers 13 Pointers to Simple Values Two major operations when a pointer is referencing a primitive To dereference the pointer value int i = 7; int j = 11; int *p = & i; // set p to point to i int *q = & j; // set q to point to j *p = *p + 3; // i now has the value 10 Change pointer value to another pointer value p = q; // i now has the value 10 Pointers should be compared only for equality. if (p == q) … while (p !=q) …

6/10/2015C++ for Java Programmers 14 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 p = q; // now p points to different object

6/10/2015C++ for Java Programmers 15 Referencing a deleted value Nothing prevents a pointer from referencing a deleted value. int * p;// global pointer variable void Set () { int i; // local variable i = 7; // give i a value (Note: i is local) p = & i; // set p to point to it } void Use () { double d; d = 3.0; d += *p; // use the value p points to ?????? // i no longer exists, memory recycled }

Value vs. Reference Parameters Pass by Value // statement in main() swap(x, y); void swap (int a, int b) {int temp; temp = a; a = b; b = temp; } Pass by Reference // statement in main() swap(x, y); void swap (int &a, int &b) {int temp; temp = a; a = b; b = temp; } 6/10/2015C++ for Java Programmers 16

Value vs. Reference Parameters Pass by Value Copy of actual parameter is passed to function Variable, constants, expressions can be passed Modifying parameter affects only local copy Safe–no external side effects Inefficient for large structures (must make local copy) Pass by Reference Address of actual parameter is passed to function Only variables (things with addresses can be passed Modifying parameter affects the original variable External side effects Efficient for large structures (only address is passed) 6/10/2015C++ for Java Programmers 17

C has only value parameters (but you can cheat) Pass by Reference // statement in main() swap(x, y); void swap (int &a, int &b) {int temp; temp = a; a = b; b = temp; } Pass by Reference (sort of) // statement in main() swap(&x, &y); void swap (int *a, int *b) {int temp; temp = *a; *a = *b; *b = temp; } 6/10/2015C++ for Java Programmers 18

C has only value parameters (Ooops – except for arrays) Arrays are always passed by reference Saves time & space Array names are base addresses int a[100]; a == &a[0]; Java has only value parameters … but when passing a reference type you are actually passing the reference (address) by value so it works just like “call by reference” 6/10/2015C++ for Java Programmers 19

6/10/2015C++ for Java Programmers 20 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; }

6/10/2015C++ for Java Programmers 21 Pointers to Pointers A pointer to a value that is itself a pointer can be declared using multiple levels of * symbols. int main (int argc, char ** argv) {... cout << "name of program " << **argv << '\n'; return 0; }

6/10/2015C++ for Java Programmers 22 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 constant int int * const q = &i; // constant pointer *p = 8; // not allowed, p points to a const int *q = 8; // allowed, q is pointing to non const int p = q; // allowed, p itself is not constant q = p; // not allowed q is constant

6/10/2015C++ for Java Programmers 23 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

6/10/2015C++ for Java Programmers 24 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 fptr fptr = & fdiv; // assign value double x = fptr(7, 14); // call ftpr directly double x = (*fptr) (7, 14); // dereference ftpr and call

6/10/2015C++ for Java Programmers 25 Pointers to Functions double 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.

6/10/2015C++ for Java Programmers 26 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 element link * firstLink = & finalElement; // set pointer to initially refer to this (*firstLink).value = 7; // these two statements firstLink->value = 7; // have the same effect

6/10/2015C++ for Java Programmers 27 Pointers to Structure for (link *p = aList; p != &finalElement; p = p->next) cout value << " ";

6/10/2015C++ for Java Programmers 28 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 large p[-4] = 12; // index value too small

6/10/2015C++ for Java Programmers 29 Pointer Arithmetic It is legal to perform arithmetic on pointers. char * text = "... some text "; // p++ advances pointer to next location for (char * p = text; *p != '\0'; p++) if (isVowel(*p)) cout << "vowel value is " << *p << "\n";

6/10/2015C++ for Java Programmers 30 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. A pointer is a variable that can contain a reference

6/10/2015C++ for Java Programmers 31 References A reference is declared by using the ampersand. int i = 7; int & j = i;// j is an alias for i j++;// i is now 8 i += 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];

6/10/2015C++ for Java Programmers 32 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++; } int main ( ) { int j = 5; passTest(j); cout << j << '\n'; return 0; }

6/10/2015C++ for Java Programmers 33 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); }

6/10/2015C++ for Java Programmers 34 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 structures can be returned by reference.

6/10/2015C++ for Java Programmers 35 Example of Reference as Result class 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; // danger, reference to local which will soon be recycled }