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.

Slides:



Advertisements
Similar presentations
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Advertisements

Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
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 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 10: Pointers.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointer Data Type and Pointer Variables
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
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,
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified by use by the MSU CMPS Dept. Chapter 10:
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation 9.8.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
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.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
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.
Pointers Data Structures CSI 312 CSI Dept. Dr. Yousef Qawqzeh.
Pointers CSC1201: Programming Language 2. Topics Pointers ▫Memory addresses ▫Declaration ▫Dereferencing a pointer ▫Pointers to pointer.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Pointers What is the data type of pointer variables?
Standard Version of Starting Out with C++, 4th Edition
Chapter 9: Pointers.
Lecture 9 Files, Pointers
Chapter 10: Pointers Starting Out with C++ Early Objects
Pointers and Pointer-Based Strings
Pointer.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Chapter 10: Pointers Starting Out with C++ Early Objects
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Chapter 9: Pointers.
Alternate Version of STARTING OUT WITH C++ 4th Edition
Constant pointers and pointers to constants
Pointers and Pointer-Based Strings
Standard Version of Starting Out with C++, 4th Edition
Dynamic Memory Allocation
Pointers.
Presentation transcript:

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 8.5 Initializing Pointers

3 Topics 8.6 Comparing Pointers 8.7 Pointers as Function Parameters 8.8 Dynamic Memory Allocation 8.9 Returning Pointers from Functions

4 C++ Variables A Variable has all of the following attributes: 1. name 2. type 3. size 4. value 5. storage class static or automatic 6. scope where it is known in the program 7. linkage use of extern and static qualifiers 8. address the address in memory of the variable

5 8.1 Getting the Address of a Variable Each variable in a program is stored at a unique address Use address operator & to get the address of a variable: int num = -23; cout << &num; // prints address // in hexadecimal

6 8.2 Pointer Variables Pointer variable (pointer): variable that holds an address Can perform some tasks more easily with an address than by accessing memory via a symbolic name: Accessing unnamed memory locations Array manipulation etc.

7 Pointer Variables Definition: int *intPtr; // can hold the address of an int Read as: intPtr is a pointer to an integer Spacing in definition does not matter: int *intPtr; // same as above

8 Chapter 8 – Pointers char int double

9 Pointer Variables Assignment: int *intPtr; intPtr = &num; Memory layout: You access num using intPtr and the indirection operator ( * ) cout << *intPtr << endl; // prints 25 //the indirection operator dereferences a variable numintPtr 25 0x4a00 address of num : 0x4a00

The Relationship Between Arrays and Pointers An array name is a constant pointer to the first element in an array. It holds an address. int vals[] = {4, 7, 11}; cout << vals; // displays 0x4a00 cout << vals[0]; // displays starting address of vals : 0x4a00

11 The Relationship Between Arrays and Pointers An array name can be used as a pointer constant: int vals[] = {4, 7, 11}; cout << *vals; // displays 4 A Pointer can be used as an array name: int *valPtr = vals; cout << valPtr[1]; //displays 7 cout << *(valPtr+1); //displays 7 cout << valPtr; //displays address of vals

12 Pointers in Expressions Given: int vals[] = {4,7,11}, *valPtr; valPtr = vals; What is valPtr + 1 ? It means (address in valptr ) + (1 * size of an int) cout << *(valPtr+1); //displays 7 cout << *(valPtr+2); //displays 11 Must use ( ) in expression

13 Array Access Array elements can be accessed in many ways: Use of [ ] subscript and * offset notation Array access methodExample array name and [] vals[2] = 17; pointer to array and [] valPtr[2] = 17; array name and pointer arithmetic *(vals + 2) = 17; pointer to array and pointer arithmetic *(valPtr + 2) = 17;

14 Array Access Conversion: vals[i] is equivalent to *(vals + i) No bounds checking performed on array access, whether using array name or a pointer

Pointer Arithmetic OperationExample int vals[] = {4,7,11}; int *valPtr = vals; ++, -- valPtr++; // points at 7 valPtr--; // now points at 4 +, - (pointer and int ) cout << *(valPtr + 2); // 11 +=, -= (pointer and int ) valPtr = vals; // points at 4 valPtr += 2; // points at 11 - (pointer from pointer) cout << valPtr – val; // difference //(number of ints) between valPtr // and val

Initializing Pointers Can initialize at definition time: int num, *numPtr = &num; int val[3], *valPtr = val; int *ptr = 0; //create a pointer initialized to 0 //ptr is currently a NULL pointer Cannot mix data types: double cost; int *ptr = &cost; // won’t work Can test for an invalid address for ptr with: if (!ptr) …

Comparing Pointers Relational operators can be used to compare addresses in pointers Comparing addresses in pointers is not the same as comparing the values pointed at by pointers: if (ptr1 == ptr2) // compares // addresses if (*ptr1 == *ptr2) // compares // values

Pointers as Function Parameters A pointer can be parameter Works like reference variable to allow change to argument from within function Requires: 1) asterisk * on parameter in prototype and heading void getNum(int *ptr); // ptr is pointer to an int 2) asterisk * in body to dereference the pointer cin >> *ptr; 3) address as argument to the function getNum(&num); // pass address of num to getNum

19 Pointers as Function Parameters void swap(int *x, int *y) {int temp; temp = *x; *x = *y; *y = temp; } int num1 = 2, num2 = -3; swap(&num1, &num2);

Pointers as Function Parameters A pointer can be used as a function parameter. It gives the function access to the original argument, much like a reference parameter does. void double ( int &); // reference void double ( int * ); // pointer a reference is a "constant" pointer

21 Keyword const with pointers/data ( not in book! ) [ const ] * [ const ] constant dataconstant pointer int x = 100; const int * const xPtr = &x; // xPtr is a constant pointer to an integer constant

22 Creating a constant pointer The const qualifier is used by a programmer to inform the compiler that the value of a particular variable should not be modified. The const qualifier can be applied to a pointer making it a constant pointer. int x = 100, y = 10; int * const intPtr = &x; // defines intPtr as a constant pointer to an integer intPtr = &y; // error! intPtr is a constant pointer *intPtr += 100; // x now contains 200 (constant pointer, not data) A constant pointer cannot be assigned a new address

23 Creating a pointer to constant data A pointer can be declared to point to a constant type. In this situation the pointer can be assigned a new address but the data in the object it points to cannot be modified. int x = 100, y = 10; const int * intPtr = &x; // intPtr is a pointer to an integer constant intPtr = &y; // intPtr now points to y *intPtr += 100; // error! Cannot change constant data A constant variable cannot be updated through a dereferenced pointer.

Dynamic Memory Allocation A program can allocate storage for a variable while it is running Use the new operator to allocate memory: double *dblPtr; dblPtr = new double; new returns the address of a memory location if it is successful or 0 ( NULL ) if not.

25 Dynamic Memory Allocation You can use new to dynamically allocate an array: double *arrayPtr; cout << "How many real numbers? "; cin >> count; arrayPtr = new double[count];//count is a variable! You can use subscript or offset notation to access the array elements. for (int i = 0; i < count; i++) arrayptr[i] = i * i; or for (int i = 0; i < count; i++) *(arrayptr + i) = i * i;

26 Releasing Dynamic Memory Use delete to free dynamic memory: delete fPtr; //single element Use [] to free a dynamic array: delete [] arrayPtr; //array of elements Only use delete with dynamically allocated memory!

Returning Pointers from Functions A pointer can be the return type of function: int* newNum(); Function must not return a pointer to an automatic local variable in the function Function should only return a pointer: to data that was passed to the function as an argument to dynamically allocated memory

Returning Pointers from Functions char *getName( ) { char name[81]; cout<<"Enter your name: "; cin.getline(name, 81); return name; //not allowed } char *getName(char *name) { cout<<"Enter your name: "; cin.getline(name, 81); return name; } char *getName( ) { char *name; name = new char[81]; cout<<"Enter your name: "; cin.getline(name, 81); return name; }

29 A Final array example #include using namespace std; int main() { int sales[3][4] = { {100,500,200,250}, {300,250,400,500}, {450,350,400,200} }; cout << "The sales array is defined as: int sales[3][4]" << endl << endl; cout << "The value of sales is: " << sales << endl; for (int j =0; j<3; j++) cout << "The value of sales[" << j << "] is: " << sales[j] << endl; cout << endl; for (int m=0; m<3; m++) for (int n=0; n<4; n++) cout << sales[m][n] << " "; cout << endl; for (m=0; m<3; m++) for (int n=0; n<4; n++) cout << *(*(sales+m)+n) << " "; // array name – offset notation for a cout << endl << endl; // two-dimensional array return 0; } *(*(*(*(name + d1)+d2)+d3)+d4)… // equivalent to name[d1][d2][d3][d4]… name is the name of the array or pointer d1, d2, d3 … represent values used for the different dimensions in a multi-dimensional array

30 The sales array is defined as: int sales[3][4] The value of sales is: 0x0012FF50 The value of sales[0] is: 0x0012FF50 The value of sales[1] is: 0x0012FF60 The value of sales[2] is: 0x0012FF