This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Programming and Data Structure
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the design and concepts behind pointer arithmetic ❏ To write.
Kernighan/Ritchie: Kelley/Pohl:
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compiling time * Dynamic Memory.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compilation time * Dynamic Memory.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
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.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
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.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
Pointers Applications
Pointers. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program execution.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
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.
Pointers OVERVIEW.
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.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Object-Oriented Programming in C++
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.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the relationship between arrays and pointers ❏ To understand the.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Object Lifetime and Pointers
Dynamic Storage Allocation
Computer Organization and Design Pointers, Arrays and Strings in C
Motivation and Overview
Pointers Revisited What is variable address, name, value?
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Object Oriented Programming COP3330 / CGS5409
Pointers and dynamic objects
Pointers.
Objectives You should be able to describe: Addresses and Pointers
Dynamic Objects.
Pointers and dynamic objects
Pointers and dynamic objects
Pointers and pointer applications
Pointers, Dynamic Data, and Reference Types
Dynamic Objects.
Presentation transcript:

This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson Learning, COMP103 - Pointers1 Pointers (Chapter 9) A pointer keeps the address of a memory cell that is used for storing and accessing data int a;

COMP103 - Pointers2 Why Pointers? 1. Curious – like to know where exactly is your variable in memory, the content of a certain memory location. 2. Not sure how much memory you need for your program int A[size];

COMP103 - Pointers3 Computer Memory Memory can be conceptualized as a linear set of “cells” (one byte in size) with a number, referred to as “address” associated with each cell. Memory cellsVariablesAddress a achar

COMP103 - Pointers4 Variables’ data are stored in these cells int a = 10; char mystr[5]=“hello”; Variable Data and Memory Note: Different types of data require different amounts of memory Computer Memory h h e e l l l l o o 4 bytes 5 single bytes

COMP103 - Pointers5 Variables’ data are stored in these cells char mystr[]=“hello”; int a = 10; a = 20; Variable Data and Memory An assignment changes the data in the memory location Variable a is bound to this memory location! Computer Memory h h e e l l l l o o 4 bytes 5 single bytes

COMP103 - Pointers6 Pointer Constants (or memory address) We can think memory addresses as Pointer Constants Pointer Constants int a = 10; To

COMP103 - Pointers7 Address Operator (&) Address operator (&) provides a pointer constant of the variable: usage &variable_name Pointer Constants int a = 10; &a To

COMP103 - Pointers8 Figure 9-4 (p.415) Address Operator & &variable gives the address of the variable &a and &b. Result: (note: this does not work in Visual C++!!) Variable name Address

COMP103 - Pointers9 Pointer Variable A pointer variable is a variable that stores a memory location (address) Pointers are declared using a “*” after the type int a = 10; // a pointer variable!!! int *p; p = &a; Pointer Constants a p To

COMP103 - Pointers10 Pointer Variable Declaration Type of data at the Memory location Figure 9-10 (p.419) Variable Name

COMP103 - Pointers11 Declaring Pointer Variables Figure 9-11 (p.419)

COMP103 - Pointers12 Don’t get confused Pointer variable, p does not hold the value of a points to the memory location of a is a variable itself has its own memory location ( ) Pointer Constants a p To int a; int *p; a=10; P = &a;

COMP103 - Pointers13 Multiple Pointers to a Variable We may have multiple pointer variables pointing to the same memory cell! What are their values? a = ? &a = ? p = ? q = ? Figure 9-7 (p.417)

COMP103 - Pointers14 Multiple Pointers to One Variable How? int a, *p, *q, *r; p = &a; q = &a; r = q; Figure 9-6 (p.425)

COMP103 - Pointers15 Multiple Pointers to a Variable int x; int *p, *q; p = &x; q = &x; Changing the variable x does not affect the pointers p and q Figure 9-8 (p.418)

COMP103 - Pointers16 Un-initialized Pointers Figure 9-12 (p.421)

COMP103 - Pointers17 Initialize Pointer Variables int *p = &x; // set a pointer to nothing int *p = NULL; Figure 9-13 (p.421)

COMP103 - Pointers18 Multiple Bindings The power of pointers! A pointer may be used to access different variables. p = &a p = &b p = &c Figure 9-15 (p.424)

COMP103 - Pointers19 Using pointers - Indirection (*) We can use the pointer variable to access the variable it “points” to by Placing a * before a pointer variable, p  refers to the content of the address of the variable given in p. int a, *p; a=5; p = &a; cout << p << *p; Result: This is sometimes called “ de-referencing” the pointer 5 a p Address

COMP103 - Pointers20 Address Operator (&) and Indirection (*) & & * * inverse operators Example: int x=5; cout << *(&x); // *(&x) is just x Indirection Address Operator &a reads “give me the memory address of the variable a” *p reads “give me the content of the memory address which is stored in the pointer variable p”

COMP103 - Pointers21 Indirection Operator * Using the indirection operator * Assume: p = &x; Possible ways of adding 1 to variable x: x++; x = x + 1; *p = *p + 1;

COMP103 - Pointers22 Add Two Numbers using Pointers How do we achieve the following effects using pointers? r = a + b Figure 9-14 (p.423)

COMP103 - Pointers23 More Examples Assume: int *p, *q; p = &x; q = &x; Figure 9-8 (p.418)

COMP103 - Pointers24 Dereferencing garbage pointers int a = 0; int *p; a = a + *p; // What will happen????

COMP103 - Pointers25 References vs. Pointers SUPERMAN (same person [reference]) CLARK KENT PERSON (Pointing to Superman [two different people]) *PERSON = Superman (What is he pointing to? Superman)

COMP103 - Pointers26 References versus Pointers Reference and pointers are different a num memory A reference shares the same memory location with other variables. int a; int &num = a; // num IS a A pointer is a variable. It points to a memory location. You have to use the (*) indirection operator to access the memory location at ‘a’; int a; int *p = &a; Cout << *p // same a ap 6 6

COMP103 - Pointers27 Parameter Passing - by Value Variables a and x use different memory cells. different copies Figure 9-17(a) (p.426)

COMP103 - Pointers28 same copy Parameter Passing - by Reference Variables a and x share the same memory cell. Figure 9-17(b) (p.426)

COMP103 - Pointers29 Parameter Passing - by Pointers Pointer variables, px and py refer to the memory cells of a and b. Figure 9-17(c) (p.417)

COMP103 - Pointers30 Pointers as Formal Parameters When we use pointer variables as formal parameters, we achieve the same effects of parameter passing by reference. by-reference: void exchange(int &x, int &y) by-pointer: void exchange(int *px, int *py)

COMP103 - Pointers31 Functions Returning Pointers Figure 9-18 (p.427)

COMP103 - Pointers32 Note in returning pointers Never return a pointer to a local variable. You’ll get a warning message Must point to a variable in the calling function void main() { int a, b, *p; … p = smaller( &a, &b ); … } int *smaller (int *px, int *py) { int temp = (*px < *py)? *px : *py; return (&temp); } This is bad! Don’t do it.

COMP103 - Pointers33 Pointer Indirection (Pointers to Pointers) What is a? &a? *a? p? &p? *p? **p? q? &q? *q? **q? 58 Figure 9-19 (p.428)

COMP103 - Pointers34 Pointers Indirection How to access a from p? *p How to access a from q? **q How to access a from r? ***r Figure 9-20 (p.429) 58

COMP103 - Pointers35 Casting Pointers (DO NOT DO!) What if we want to have pc pointing to a? Warning: You're advised not to cast pointers unless absolutely necessary. pc = (char *) &a; Figure 9-21 (p.433)

COMP103 - Pointers36 Pointer Types Must Match Figure 9-22 (p.433)

COMP103 - Pointers37 Lvalue vs Rvalue (Ch 9-10,p ) An C++ expression is either a rvalue or lvalue. A rvalue expression appears at the right of an assignment. It refers to a value that be assigned to a memory cell, i.e. can be used to supply a value for further use, e.g. examine or copy the value. Examples: x= 5; y= a+2; z=a*6;x=a[2]+3; i=i++; A lvalue expression appears at the left of an assignment. It identifies a memory cell that is going to receive a rvalue, i.e. the memory cell is being modified. Example: a = …a[5] = …(a) = …*p = …

COMP103 - Pointers38 Arrays and Pointers The name of an array points only to the first element not the whole array, i.e. the variable name of an array is a pointer variable. Figure 9-25 (p.443)

COMP103 - Pointers39 Array Name is a pointer constant Example on p.443 of text (where is the array in memory?) #include void main() { // Demonstrate array name is a pointer constant int a[5]; cout << "Address of a[0]: " << &a[0] << endl << "Name as pointer: " << a << endl; } /* result: Address of a[0]: 0x0065FDE4 Name as pointer: 0x0065FDE4 */

COMP103 - Pointers40 Dereference of An Array Name Figure 9-26 (p.444) How to obtain the value of a[0] using pointer operator, “*”?

COMP103 - Pointers41 Array Names as Pointers To access an array, any pointer to the first element can be used instead of the name of the array. We could replace *p by *a Figure 9-27 (p.444)

COMP103 - Pointers42 Multiple Array Pointers Both a and p are pointers to the same array. Figure 9-28 (p.445)

COMP103 - Pointers43 Pointer Arithmetic Given a pointer p, p+n refers to the element that is offset from p by n positions. Figure 9-29 (p.446)

COMP103 - Pointers44 Pointer Arithmetic & Different Types address = pointer + (offset * size of element) Figure 9-30 (p.446)

COMP103 - Pointers45 *(a+n) is identical to a[n] Dereferencing Array Pointers Figure 9-31 (p.447)

COMP103 - Pointers46 Pointers — Arrays Duality int a[10]; You can think of ‘ a ’ as really a pointer. a[0] = *(a+0) = memory at (a+0) a[1] = *(a+1) = memory at (a+1) a[2] = *(a+2) = memory at (a+2)

COMP103 - Pointers47 Example: Find Smallest (Figure 9-32, p.447) Figure 9-32 (p.447)

COMP103 - Pointers48 Pointer to 2-Dimensional Arrays table[i][j] What is **table? Figure 9-33 (p.450)

COMP103 - Pointers49 Passing an Array to a Function Caller program: func( arrayName, size ); Called program: int func( int arr [ ], int size ) {…}// preferred o r int func( int *arr, int size ) {…}// same effect Arrays are passed to a function by reference.

COMP103 - Pointers50 Variables for Multiplying Array Elements by Two Figure 9-34 (p.452) Program 9-12 (p.452)

COMP103 - Pointers51 Right-Left Rule Concept int * p; reads “p is a pointer (2) to integer (4)” int table [4]; reads “table is an array of 4 (1) integers (2)” int *a[5]; reads “a is an array of 5 (1) pointers (2) to integer (4)” int ( *a )[5]; reads “a is a pointer (2) to an array of 5 (3) integers (4)” (page 454)

COMP103 - Pointers52 Array of Pointers & Pointer to Array

COMP103 - Pointers53 MEMORY MANAGEMENT DYANMIC MEMORY STATIC MEMORY Until now, we have only learned about static memory Declaration of large memory variables (arrays) must be determined before the program is compiled. We can “ask” for memory while the program is running. We can allocate and release memory ourselves! More powerful programming ability (also more potential for errors!)

COMP103 - Pointers54 Memory Allocation { int a[200]; int *ptr = a; … } int *ptr = new int[200]; … delete [] ptr; Figure 9-35 (p.455)

COMP103 - Pointers55 Conceptual View of Memory (DYNAMIC MEMORY) Figure 9-37 (p.456)

COMP103 - Pointers56 Dynamic Memory C++ “new” keyword new ;// allocate size of the type new [size];// allocate an array Asks the Operating System to return you a pointer to a “chunk” of data.

COMP103 - Pointers57 Allocating Memory Operating System Manages dynamic memory. You have: int *p; p = new int[1000]; Ask OS to find a segment Of memory of 1000*4 btyes OS returns the address. So, you need a pointer to the type you requested. If you request, you need an pointer. If you request, you need a pointer.

COMP103 - Pointers58 Allocating memory using “ new ” int *p; new returns the address to the “start” of the memory it allocated p = new int[7]; p is assigned 8002 p[0] = *(p) = *(p+0) = ? p[1] = *(p+1) = ? p[2] = *(p+2) = ? p[0] p[1] p[2]

COMP103 - Pointers59 Dynamic Memory Allocation Request for “unused” memory from the Operating System int *p, n=10; p = new int; p = new int[100]; p = new int[n]; p new p p

COMP103 - Pointers60 Dynamic Memory Allocation Example Need an array of unknown size main() { cout << “How many students? “; cin >> n; int *grades = new int; int mark; int i; for(i=0; i < n; i++) { cout << “Input Grade for Student” << (i+1) << “ ? :”; cin >> mark; grades[i] = mark; }... printMean( grades, n ); // call a function with dynamic array... }

COMP103 - Pointers61 Dynamic Memory C++ “delete” keyword delete address; // delete one element at address delete [] address; // delete array at address How can we specify what the address is? We have pointer. Pointer variables store addresses.

COMP103 - Pointers62 Freeing (or deleting) Memory Operating System Manages dynamic memory. The memory you request by “new” is not usable by Other programs until you tell the OS you don’t need it anymore. We call this “freeing” or “releasing” or “deleting” memory. How does the OS know which piece of memory you are freeing? You give it the address. Int *p; p = new int [1000]; delete [] p; // delete (or free) the array at p NOTICE, the value of p will not change! However, it is now no longer pointer to value memory. Allocated Memory Free this Memory. OS marks it as available.

COMP103 - Pointers63 Freeing (or deleting) Memory Figure 9-40 (p.460)

COMP103 - Pointers64 Freeing (or Deleting) memory “ delete ” is a keyword delete ; // a variable example: int a; int *p=&a; delete p; delete [] ; // an array example: int *p = new int[1000]; delete [] p;

COMP103 - Pointers65 Dynamic Memory Dynamic Memory is very powerful C++ trusts you as the programmer to manage you own memory While this gives you lots of control, it is easy to make mistakes. Dynamic memory bugs are the most common of large software written in C++.

COMP103 - Pointers66 The Dangling Pointer Bug Be careful when you delete memory pointed to by p, you are not erasing a location that some other pointer q is pointing to. int *p, *q; P = new int; q = p; delete p; // q is a dangling pointer p q int p q delete p

COMP103 - Pointers67 Memory Leak Problem (bug) Make sure to delete memory when finished int *p; p = new int[100]; int a; NO ONE HAS ACCESS TO THIS MEMORY 100 integers p = &a; a a 100 integers a a This memory is un-addressable And it is reserved until your program terminates (it has leaked from the system)

COMP103 - Pointers68 Dynamic Memory Allows you to create “logical” structures by piecing together pointers + dynamic memory For example, how could we build a 2D array using Dynamic Memory?

COMP103 - Pointers69 A Dynamic 2D Array – An array of pointers int **table; // a ragged array Figure 9-41 (p.461)

COMP103 - Pointers70 Allocation of 2D Array int **data; int rows=3, cols=4; data = new int*[ rows ]; Computer’s Memory data = data[i] is a int * (points to int!) // allocate row’s data for(int i=0; i < rows; i++) { data[i] = new int[cols]; } i=0 data[i] = i= i= i=1 data[i] = i= i=2 data[i] = // Initialize data for(i=0; i < rows; i++) for(int j=0; j< cols; j++) { data[i][j] = 0; // or *(*(data+i)+j)=0 } (array of int *)

COMP103 - Pointers71 Deleting a 2D Array Computer’s Memory // delete row’s data for(int i=0; i < rows; i++) { delete [ ] data[i]; } delete memory at data[0] = delete memory at data[1] = delete memory at data[2] = i= i= i= DELETED delete memory at data = delete [ ] data;

COMP103 - Pointers72 Using Dynamic Arrays Figure 9-43 (p.465)

COMP103 - Pointers73 Implementation of Dynamic Array Figure 9-44 (p.465) Complete examples Programs 9-15 to 9-23, pp

COMP103 - Pointers74 Summary Introduced Pointers and Dynamic Memory Pointers are special variables that point to memory locations New declaration int *p; char *p; int **p; char ***p; 2 new operators p = &a; // address of a *p = 5; // Indirection operator *(p)

COMP103 - Pointers75 Summary Pointers relationship to arrays int a[10]; int *p; p = a; // a is really a pointer too! p = &a[1]; Passing pointers to functions Pointer Arithmetic *(a+1) same as a[1] *(a+9) same as a[9]

COMP103 - Pointers76 Summary Dynamic Memory new and delete calls int *p = new int[100]; int *a = new int; delete a; delete [] p; Complex Uses for Dynamic Memory Example: Dynamic 2D array int **table = new int*[3]; tables[0] = new int[10]; tables[1] = new int[2]; tables[2] = new int[100];

COMP103 - Pointers77 Summary: Pointers and your sanity Pointers are very powerful Allow you to directly access the computer’s memory This freedom can cause problems Remember Avoid Memory Leaks, Dangling Pointers Don’t access uninitialized pointers! Be kind to others! int *bad_student = new int[ ]; 