Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
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.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Pointers. COMP104 Pointers / Slide 2 Pointers * A pointer is a variable used for storing the address of a memory cell. * We can use the pointer to reference.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Review of Chapter 6: The Fundamental Data Types.
Pointers. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program execution.
Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays We’ve now looked at  Pointers  Arrays  Strings.
Arrays and Pointers in C Alan L. Cox
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Lesson 9 Pointers CS 1 Lesson 9 -- John Cole1. Pointers in Wonderland The name of the song is called ‘Haddock’s Eyes’.” “Oh, that’s the name of the song,
 2007 Pearson Education, Inc. All rights reserved C Pointers.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
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.
Dynamic memory allocation and Pointers Lecture 4.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
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.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Integer Types short month; // half of a machine word int car; // one machine word unsigned long distance; Character Types char c = ‘\0’; // one byte char.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Review 1 List Data Structure List operations List Implementation Array Linked List.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
Pointers *, &, array similarities, functions, sizeof.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
General comments [1]  array is a fixed sized group in which the elements are of the same type  The general form of array's definition is as follows:
1 Object-Oriented Programming Using C++ A tutorial for pointers.
Pointer. lvalues In C++, any expression that refers to an internal memory location is called an lvalue Appear on left side of assignment statement e.g.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
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.
1. Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Reminders: Have you filled out the questionnaire in Moodle? (3 left – as of last night). Office hours.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Pointers  * symbol and & symbol  Pointer operations  Pointer.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
C++ Lesson 1.
Pointers What is the data type of pointer variables?
Motivation and Overview
Pointers and Pointer-Based Strings
Student Book An Introduction
Lecture 6 C++ Programming
Chapter 9: Pointers.
C++ Pointers and Strings
Pointers and Pointer-Based Strings
Pointers and dynamic objects
CISC/CMPE320 - Prof. McLeod
C++ Pointers and Strings
Presentation transcript:

Pointers & References

Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References

Pointer Declarations Use an asterisk (*) int* p; –Read “p is a pointer to an int” Must always indicate type pointed to –No such thing as “just a pointer” –Pseudo-exception: void * (will see shortly) The only thing you can do with a void* is hold it Must cast to a concrete type to dereference it

Pointers to Pointers Occasionally use 2 levels Given int ** p; **p is an int => *p is a pointer to an int => p is a pointer to a pointer to an int

// ptr2ptr.cpp: Pointers to pointers #include using namespace std; int main() { int i = 7; int* ip = &i; int** ipp = &ip; cout << "Address " << ip << " contains " << *ip << endl; cout << "Address " << ipp << " contains " << *ipp << endl; cout << "**ipp == " << **ipp << endl; } // Output: Address 0012ff88 contains 7 Address 0012ff84 contains 0012ff88 **ipp == 7

Pointer Addition Add an integer to a pointer Moves the pointer up (if +) or back (if -) in memory that many objects – i.e., p+n increases address by n*sizeof(*p) Can only be used within an array –Except you can move one past the end –But you can’t dereference there

Pointer Subtraction Yields number of objects between two objects pointed to Could be negative Special type to hold result (ptrdiff_t) –Usually a typedef for long

About typedef “Type definition” Creates synonyms for existing types –For convenience and portability –Used heavily in STL typedef char myChar; typedef unsigned int wchar_t; typedef long ptrdiff_t; typedef unsigned long size_t; typedef int A5[5]; –A5 a; // Same as int a[5]

#include using namespace std; int main() { float a[] = {1.0, 2.0, 3.0}; // Increment a pointer: cout << "sizeof(float) == " << sizeof(float) << endl; float* p = &a[0];// or just a; cout << "p == " << p << ", *p == " << *p << endl; ++p; cout << "p == " << p << ", *p == " << *p << endl; // Subtract two pointers: ptrdiff_t diff = (p+1) - p; cout << "diff == " << diff << endl; diff = static_cast (p+1) – static_cast (p); cout << "diff == " << diff << endl; } /* Output: sizeof(float) == 4 p == 0012ff80, *p == 1 p == 0012ff84, *p == 2 diff == 1 diff == 4 */

Pointers and const Two degrees of freedom –Is the pointer itself const? –Or is the thing pointed to const? Usually the latter case (pointer-to-const) All depends on where you put the const –Relative to the asterisk Used extensively throughout the C library

Pointers and const const before the asterisk means that the contents is const const after the asterisk means that the pointer is const const char* p1; // *p1 = 'c' illegal; ++p1 OK char* const p2; // *p2 = 'c' OK; ++p2 illegal const char* const p3; // no changes at all allowed

Generic Pointers void * Allows holding a pointer to any type –Can store any pointer in a void* –Must explicitly cast back to original type to use Used often as function parameters Useful for: –treating any object as a sequence of bytes –implementing generic containers

void* memcpy(void* target, const void* source, size_t n) { // Copy any object to another char* targetp = static_cast (target); const char* sourcep = static_cast (source); while (n--) *targetp++ = *sourcep++; return target; } int main() { float x = 1.0, y = 2.0; memcpy(&x, &y, sizeof x);// same as x = y cout << x << endl; } 2

Incomplete Types Sometimes it is necessary to introduce a pointer to a type that hasn’t yet been fully defined –These are called incomplete types For example, the mutual reference problem: class A; class B {A* a; …}; class A {B* b; …}; Another example: pImpl idiom

Pointers and Arrays The name of an array becomes a pointer to its 1st element –Except as an operand to sizeof In other words: a is the same as &a[0] In other words: *a == a[0] More generally: a + i == &a[i] Or: *(a + i) == a[i]

Multi-dimensional Arrays Don’t really exist! “Arrays of arrays” instead int a[2][3] –an array of 2 elements –each element is an arrays of 3 ints –what is sizeof(a[0])?

Question How do you declare a pointer for the following: ??? = new int[2][3];

Partial Answer All arrays are considered 1-dimensional The expression new int[2][3] creates an array of two elements It returns a pointer to the first element We must have the condition: –sizeof(*p) == 3 * sizeof(int) So p must point to something with size 12! –(on a 32-bit machine, of course)

Higher and Deeper Repeat the process on the 3-d array: int a[2][3][4];

How does istream::get work? char c; cin.get(c);// reads next input byte into c cout << c;// prints the byte read as a char

References An alias for another memory location Can be function parameters –Implements “call by reference” –Implicit pointer indirection Does not exist in Java Can also be local –Merely another name for an existing variable Can be return values –Often used by operator[ ] –Appears throughout STL

References are Aliases #include int main() { using namespace std; int i = 7; int& r = i; ++r; cout << i << endl;// 8 }

Reference Parameters #include using namespace std; void swap(int& x, int& y) { int temp = x; x = y; y = temp; } int main() { int i = 1, j = 2; swap(i,j); cout << "i == " << i << ", j == " << j; } /* Output: i == 2, j == 1 */

Reference Returns #include int a[4] = {0,1,2,3}; int index = 0; int& current()// Returns a reference { return a[index]; } int main() { using namespace std; current() = 10; // replace a[0] index = 3; current() = 20; // replace a[3] for (int i = 0; i < 4; ++i) cout << a[i]; cout << endl; } /* Output: */

const Reference Parameters When you won’t be changing the value The “best of both worlds” –Efficiency of call-by-reference –Safety of call-by-value Because calling argument is protected from change (Almost) Always pass objects by (const) reference

An Employee Class class Employee { string name; double rate; double timeWorked; public: Employee(const string& ename, double erate) : name(ename) { rate = erate; } string getName() const {return name;} double getRate() const {return rate;} double getTimeWorked() const {return timeWorked;} void recordTime(double etime) {timeWorked = etime;} double computePay() const; };

double Employee::computePay() const { const double& hours = timeWorked; if (hours > 40) return 40*rate + (hours - 40)*rate*1.5; else return rate * hours; } int main() { using namespace std; Employee e("John Hourly",16.50); e.recordTime(52.0); cout << e.getName() << " gets ” << e.computePay() << endl; } John Hourly gets