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.

Slides:



Advertisements
Similar presentations
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Advertisements

Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
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.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Computer Science II Exam I Review Monday, February 6, 2006.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays We’ve now looked at  Pointers  Arrays  Strings.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CSE 332: C++ functions Review: What = and & Mean In C++ the = symbol means either initialization or assignment –If it’s used with a type declaration, it.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
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.
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.
CSE 332: C++ execution control statements Overview of C++ Execution Control Expressions vs. statements Arithmetic operators and expressions * / % + - Relational.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ Memory Overview 4 major memory segments Key differences from Java
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.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
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”
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.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Variables and memory addresses
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Announcements You will receive your scores back for Assignment 2 this week. You will have an opportunity to correct your code and resubmit it for partial.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
C++ Functions A bit of review (things we’ve covered so far)
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
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.
Motivation for Generic Programming in C++
LESSON 06.
Motivation and Overview
Pointers and Pointer-Based Strings
Student Book An Introduction
Pointers and References
Built-In (a.k.a. Native) Types in C++
Overloading functions
Pointers and Pointer-Based Strings
Data Structures and Algorithms Introduction to Pointers
Pointers and dynamic objects
SPL – PS2 C++ Memory Handling.
Presentation transcript:

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 itself –Also known as “aliasing” Two ways to do this –Indirectly, via a pointer Gives the address (in memory) of the object Requires the user to do extra work: dereferencing –Directly, via a reference Acts as an alias for the object User interacts with reference as if it were the object itself

CSE 332: C++ pointers, arrays, and references Untangling Operator Syntax SymbolUsed in a declaration Used in a definition unary & (ampersand) reference int i; int &r = i; address-of p = &i; unary * (star) pointer int * p; dereference (what’s pointed to) *p = 7; -> (arrow) member access via pointer cp->add(3);. (dot) member access (same syntax for either reference or object) c.add(3);

CSE 332: C++ pointers, arrays, and references What’s a Pointer? A variable holding an address –Of what it “points to” in memory Can be untyped void * v; // can point to any type However, usually they’re typed –Checked by compiler –Can only be assigned addresses of variables of the type to which it can point int * p; // can only point to int Addresses: garbage, something, nothing –When created: int * p = i; vs. int * q; q = 0; // now it points to nothing p = NULL; // bad idea, not portable 0x7fffdad0 7 int i int * p 3 const int j 7 int k

CSE 332: C++ pointers, arrays, and references What’s a Reference? A variable holding an address –Of what it “refers to” in memory But with a nicer interface –An alias to the object –Hides indirection from programmer Must be typed –Checked by compiler –Again can only refer to the type to which it can point int &r = i; // can only refer to int Must always refer to something –Must be initialized, cannot be changed 0x7fffdad0 7 int i int &r

CSE 332: C++ pointers, arrays, and references Aliasing and Pointers int main(int, char *[]) { int i = 0; int j = 1; int *p = &i; int *q = &i; *q = 6; // i is now 6, j is still 1 cout << i << “ ” << j; } Distinct variables alias different memory locations –E.g., i and j An object and all the pointers to it (when dereferenced) alias the same location –E.g., i, *p, and *q Assigning a new value to i, *p or *q changes value seen through the others But does not change value seen through j 0xefffdad0 6 int i int *p 1 int j 0xefffdad0 int *q

CSE 332: C++ pointers, arrays, and references Location and Value Comparisons Pointers may be compared for equality –Same as comparing addresses of what pointers point to (memory locations: l-values) Contents of what pointers point to may be compared, too (r-values) First implies second, not other way around p == q&*p == &*q *p == *q 0xefffdad0 5 int i int *p 5 int j 0xefffdbd0 int *q

CSE 332: C++ pointers, arrays, and references Const Pointers and Pointers to Const Types int main (int, char *[]) { const int i = 0; int j = 1; int k = 2; // pointer to int int * w = &j; // const pointer to int int * const x = &k; // pointer to const int const int * y = &i; // const pointer to const int const int * const z = &j; } Make promises via the const keyword in pointer declaration: –not to change pointer itself –not to change value it aliases –can also promise neither/both Read declarations right to left In this example, can change –w and what it points to –what x points to but not x –y but not what it points to –neither z nor what it points to A pointer to a non-const type cannot point to a const variable –w and x can’t point to i

CSE 332: C++ pointers, arrays, and references Aliasing and References int main(int, char *[]) { int i = 0; int j = 1; int &r = i; int &s = i; r = 8; // i is now 8, j is still 1 cout << i << “ ” << j; } An object and all the references to it alias the same location –E.g., i, r, and s Assigning a new value to i, r or s changes value seen through the others But does not change value seen through j 0xefffdad0 8 int i int &r 1 int j 0xefffdad0 int &s

CSE 332: C++ pointers, arrays, and references Const References int main (int, char *[]) { const int i = 0; int j = 1; // non-const reference // r can’t refer to i int &r = j; // this is ok, though const int &s = i; const int &t = j; } Remember: references must refer to something –Can’t be 0 (or NULL) –Except through bad tricks like int *p = 0; int & r = *p; Also, once initialized, references cannot be changed –E.g., can’t redirect t to i –In Java, can re-assign references –In C++, you cannot Const reference –Promise not to change what’s aliased –E.g., can’t use t to change j Can’t have a non-const reference alias a const variable –Reverse is OK

CSE 332: C++ pointers, arrays, and references Review: Function Parameter Passing int main (int, char *[]) { int h = -1; int i = 0; int j = 1; int k = 2; return func(h, i, j, &k); } int func(int a, const int &b, int &c, int *d) { ++a; c = b; *d = c; ++d; return 0; } By value –Makes a copy i.e., of h into local variable a –++a does not change h By reference –Alias for passed variable –c = b changes j –can’t change b (or i ): const Can pass address by value –And then use address value to change what it points to *d = c; // changes k ++d; // changes local pointer

CSE 332: C++ pointers, arrays, and references References to Pointers int main (int, char *[]) { int j = 1; int &r = j; // r aliases j int *p = &r; // p really // points to j int * &t = p; // t aliases p } Can’t have a pointer to a reference –But can point to what the reference aliases Address-of operator on a reference to a variable –Gives address of variable –not of the reference itself Reference to a pointer –An alias for the pointer … not for what it points to –Useful to pass a pointer to code that may change it 0xefffdad0 1 int j int &r int *p 0xefffdad0 0xefffad24 int * &t

CSE 332: C++ pointers, arrays, and references Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range” of items) –Allows some useful tricks with addressing –Can make certain algorithms more efficient Array indexes are another form of aliasing –Can interchange with pointer dereferencing –Can do index arithmetic, like pointer arithmetic Arrays can be indexed by enumerated types –Allows labels to be used instead of numbers

CSE 332: C++ pointers, arrays, and references Pointers and Arrays int main (int, char **) { int arr[3] = {0, 1, 2}; int * p = &arr[0]; int * q = arr; // p, q both point to arr[0] ++q; // now q points to arr[1] } Array variable itself behaves like a const pointer int * const arr; Set pointers to the start of the array –Using address of 0 th element –Or, just using array name Pointer arithmetic –Adding number n to a pointer Changes pointer’s value By n times the size of the type to which it points Moves pointer n array positions –E.g., value in q is increased by sizeof(int) by ++ q 0xefffdad0 2 int arr[3] int *p 1 0xefffdad4 int *q 0 Notice alternative declaration

CSE 332: C++ pointers, arrays, and references Arrays of (and Pointers to) Pointers int main(int argc, char * * argv) { for (int i = 0; i < argc; ++i) { cout << argv[i] << endl; } return 0; } Can have pointers to pointers Can also have an array of pointers (like a const pointer to a pointer type) E.g., argv parameter in main –Array of pointers to character strings –Could also declare as a pointer to the first pointer –Array dimension is not specified –Instead a special argument ( argc ) holds array size By convention, character strings are zero terminated –Special char is ‘\0’ not ‘0’ 0xefffbab0 char * * argv int argc 2 0xefffa0d0 hellotest\0

CSE 332: C++ pointers, arrays, and references Example Program: Enumerations and Arrays // arrays.cc // // author: Chris Gill // // purpose: definitions for array demonstration program #include "arrays.h" #include // Standard streams and manipulators. // Use symbols from the standard namespace. using namespace std; Let’s look at the header file declarations

CSE 332: C++ pointers, arrays, and references Declaring Enumerated Types for Array Indexes // arrays.h // // author: Chris Gill // // purpose: declarations for array demonstration program // same as enum friends {amy = 0, sam = 1, george = 2, // brent = 3, alice = 4, friend_count = 5}; // enum friends {amy, sam, george, brent, alice, friend_count}; // function declarations (prototypes) void print_enumeration (); void print_names (const char * * names, int size); void print_balances (int account_balances[friend_count]); Notice the contiguous values, and the count value Notice no other header files are declared, since not needed

CSE 332: C++ pointers, arrays, and references Example Program: Main Function int main (int, char *[]) { const char * names [friend_count] = {"amy", "sam", "george", "brent", "alice"}; // illustrates use of enumerated types print_enumeration (); int account_balances [friend_count]; for (int i = 0; i < friend_count; ++i) { account_balances[i] = 1000; } // pass array and its size print_names (names, friend_count); // just pass the array print_balances (account_balances); return 0; } Can initialize with known set of values Can assign dynamically using a loop and index

CSE 332: C++ pointers, arrays, and references Example Program: Enumeration Values /* prints out by iteration: by individual value: */ void print_enumeration () { cout << "by iteration: "; for (int i = amy; i <= friend_count; ++i) { cout << i << " "; } cout << endl << "by individual value: “ << amy << " " << sam << " " << george << " " << brent << " " << alice << " " << friend_count << endl; } Can’t use a variable of enumerated type just yet (no operator++ declared) Can use enumerated values directly, though

CSE 332: C++ pointers, arrays, and references Example Program: Passing Arrays /* prints out amy sam george brent alice */ void print_names (const char * names [], int size) { for (int i = 0; i < size; ++i) { cout << names [i] << " "; } cout << endl; } /* prints out */ void print_balances (int account_balances[friend_count]) { for (int i = amy; i < friend_count; ++i) { cout << account_balances[i] << " "; } cout << endl; } Pass dynamically sized array with size variable Can pass fixed-size array by itself

CSE 332: C++ pointers, arrays, and references Summary of the Course So Far We’ve focused a lot on “C-level” issues so far –Variable declarations and expressions –Statements and functions –Pointers, arrays, l-values, and r-values We’ve touched on a few additional nuances –Reference variables, exceptions, namespaces These are all a foundation for what’s next –Dynamic memory management operators –Classes, objects, inheritance, virtual functions –Templates, traits, interface polymorphism –The Standard Template Library

CSE 332: C++ pointers, arrays, and references For Next Time Topic: C++ Memory Management Assigned Readings –pages –pages –pages –pages –pages