Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.

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

Starting Out with C++, 3 rd Edition 1 Chapter 8 – Searching and Sorting Arrays.
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Pointers CS 308 – Data Structures. Getting the address of a variable You need to use the address operator & #include void main() { int num; num = 22;
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
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.
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.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CS102 Introduction to Computer Programming Chapter 7 Arrays.
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 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
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 © 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.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
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.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
Pointers, Variables, and Memory. Variables and Pointers When you declare a variable, memory is allocated to store a value. A pointer can be used to hold.
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 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.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
DCT1063 Programming 2 CHAPTER 1 POINTERS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Slide 1 of 36. Attributes Associated with Every Variable Data type Data type Actual value stored in variable Actual value stored in variable Address of.
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.
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.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
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 CSC1201: Programming Language 2. Topics Pointers ▫Memory addresses ▫Declaration ▫Dereferencing a pointer ▫Pointers to pointer.
EGR 2261 Unit 11 Pointers and Dynamic Variables
Standard Version of Starting Out with C++, 4th Edition
Chapter 9: Pointers.
Chapter 7 – Arrays.
Chapter 10: Pointers Starting Out with C++ Early Objects
Chapter 10: Pointers Starting Out with C++ Early Objects
Dynamic Memory Allocation
Chapter 9: Pointers.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Chapter 9: Pointers.
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Objectives You should be able to describe: Addresses and Pointers
Standard Version of Starting Out with C++, 4th Edition
Pointers.
Presentation transcript:

Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers

Starting Out with C++, 3 rd Edition Getting the address of a Variable The address operator (&) returns the memory address of a variable.

Starting Out with C++, 3 rd Edition 3 Figure letternumberamount

Starting Out with C++, 3 rd Edition 4 Program 9-1 // This program uses the & operator to determine a variable’s // address and the sizeof operator to determine its size. #include void main(void) { int x = 25; cout << "The address of x is " << &x << endl; cout << "The size of x is " << sizeof(x) << " bytes\n"; cout << "The value in x is " << x << endl; }

Starting Out with C++, 3 rd Edition 5 Program Output The address of x is 0x8f05 The size of x is 2 bytes The value in x is 25

Starting Out with C++, 3 rd Edition 6 Pointer Variables Pointer variables, which are often just called pointers, are designed to hold memory addresses. With pointer variables you can indirectly manipulate data stored in other variables.

Starting Out with C++, 3 rd Edition 7 Pointers are useful for the following: Working with memory locations that regular variables don’t give you access to Working with strings and arrays Creating new variables in memory while the program is running Creating arbitrarily-sized lists of values in memory

Starting Out with C++, 3 rd Edition 8 Program 9-2 // This program stores the address of a variable in a pointer. #include void main(void) { int x = 25; int *ptr; ptr = &x; // Store the address of x in ptr cout << "The value in x is " << x << endl; cout << "The address of x is " << ptr << endl; }

Starting Out with C++, 3 rd Edition 9 Program Output The value in x is 25 The address of x is 0x7e00

Starting Out with C++, 3 rd Edition 10 Figure 9-2 0x7e00 25 ptr x Address of x: 0x7e00

Starting Out with C++, 3 rd Edition 11 Program 9-3 // This program demonstrates the use of the indirection // operator. #include void main(void) { int x = 25; int *ptr; ptr = &x; // Store the address of x in ptr cout << "Here is the value in x, printed twice:\n"; cout << x << " " << *ptr << endl; *ptr = 100; cout << "Once again, here is the value in x:\n"; cout << x << " " << *ptr << endl; }

Starting Out with C++, 3 rd Edition 12 Program Output Here is the value in x, printed twice: 25 Once again, here is the value in x: 100

Starting Out with C++, 3 rd Edition 13 Program 9-4 #include void main(void) { int x = 25, y = 50, z = 75; int *ptr; cout << "Here are the values of x, y, and z:\n"; cout << x << " " << y << " " << z << endl; ptr = &x; // Store the address of x in ptr *ptr *= 2; // Multiply value in x by 2 ptr = &y; // Store the address of y in ptr *ptr *= 2; // Multiply value in y by 2 ptr = &z; // Store the address of z in ptr *ptr *= 2; // Multiply value in z by 2 cout << "Once again, here are the values of x, y, and z:\n"; cout << x << " " << y << " " << z << endl; }

Starting Out with C++, 3 rd Edition 14 Program Output Here are the values of x, y, and z: Once again, here are the values of x, y, and z:

Starting Out with C++, 3 rd Edition Relationship Between Arrays and Pointers array names can be used as pointers, and vice-versa.

Starting Out with C++, 3 rd Edition 16 Program 9-5 // This program shows an array name being dereferenced // with the * operator. #include void main(void) { short numbers[] = {10, 20, 30, 40, 50}; cout << "The first element of the array is "; cout << *numbers << endl; }

Starting Out with C++, 3 rd Edition 17 Program Output The first element in the array is 10

Starting Out with C++, 3 rd Edition 18 Figure 9-3 numbers numbers[0]numbers[1]numbers[2]numbers[3]numbers[4]

Starting Out with C++, 3 rd Edition 19 Figure 9-4 numbers numbers[0]numbers[1]numbers[2]numbers[3]numbers[4] (numbers+1)(numbers+2)(numbers+3)(numbers+4)

Starting Out with C++, 3 rd Edition 20 Program 9-6 // This program processes the contents of an array. Pointer // notation is used. #include void main(void) { int numbers[5]; cout << "Enter five numbers: "; for (int count = 0; count < 5; count++) cin >> *(numbers + count); cout << "Here are the numbers you entered:\n"; for (int count = 0; count < 5; count++) cout << *(numbers + count)<< " "; cout << endl; }

Starting Out with C++, 3 rd Edition 21 Program Output with Example Input Enter five numbers: [Enter] Here are the numbers you entered:

Starting Out with C++, 3 rd Edition 22 Program 9-7 // This program uses subscript notation with a pointer and // pointer notation with an array name. #include void main(void) { float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0}; float *floatPtr; // Pointer to a float int count; // array index floatPtr = coins; // floatPtr now points to coins array cout.precision(2); cout << "Here are the values in the coins array:\n";

Starting Out with C++, 3 rd Edition 23 Program continues for (count = 0; count < 5; count++) cout << floatPtr[count] << " "; cout << "\nAnd here they are again:\n"; for (count = 0; count < 5; count++) cout << *(coins + count) << " "; cout << endl; }

Starting Out with C++, 3 rd Edition 24 Program Output Here are the values in the coins array: And here they are again:

Starting Out with C++, 3 rd Edition 25 Program 9-8 // This program uses the address of each element in the array. #include void main(void) { float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0}; float *floatPtr; // Pointer to a float int count; // array index cout.precision(2); cout << "Here are the values in the coins array:\n";

Starting Out with C++, 3 rd Edition 26 Program continues for (count = 0; count < 5; count++) { floatPtr = &coins[count]; cout << *floatPtr << " "; } cout << endl; }

Starting Out with C++, 3 rd Edition 27 Program Output Here are the values in the coins array:

Starting Out with C++, 3 rd Edition Pointer Arithmetic Some mathematical operations may be performed on pointers. –The ++ and – operators may be used to increment or decrement a pointer variable. –An integer may be added to or subtracted from a pointer variable. This may be performed with the +, - +=, or -= operators. –A pointer may be subtracted from another pointer.

Starting Out with C++, 3 rd Edition 29 Program 9-9 // This program uses a pointer to display the contents // of an integer array. #include void main(void) { int set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int *nums, index; nums = set; cout << "The numbers in set are:\n"; for (index = 0; index < 8; index++) { cout << *nums << " "; nums++; }

Starting Out with C++, 3 rd Edition 30 Program continues cout << "\nThe numbers in set backwards are:\n"; for (index = 0; index < 8; index++) { nums--; cout << *nums << " "; }

Starting Out with C++, 3 rd Edition 31 Program Output The numbers in set are: The numbers in set backwards are:

Starting Out with C++, 3 rd Edition Initializing Pointers Pointers may be initialized with the address of an existing object.

Starting Out with C++, 3 rd Edition Comparing Pointers If one address comes before another address in memory, the first address is considered “less than” the second. C++’s relational operators maybe used to compare pointer values.

Starting Out with C++, 3 rd Edition 34 Figure 9-5 0x5A00 array[0]array[1]array[2]array[3]array[4] 0x5A040x5A080x5A0C0x5A0F (Addresses) An array of five integers

Starting Out with C++, 3 rd Edition 35 Program 9-10 // This program uses a pointer to display the contents // of an integer array. #include void main(void) { int set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int *nums = set; // Make nums point to set cout << "The numbers in set are:\n"; cout << *nums << " "; // Display first element while (nums < &set[7]) { nums++; cout << *nums << " "; }

Starting Out with C++, 3 rd Edition 36 Program continues cout << "\nThe numbers in set backwards are:\n"; cout << *nums << " "; // Display last element while (nums > set) { nums--; cout << *nums << " "; }

Starting Out with C++, 3 rd Edition 37 Program Output The numbers in set are: The numbers in set backwards are:

Starting Out with C++, 3 rd Edition 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.

Starting Out with C++, 3 rd Edition 39 Program 9-11 // This program uses two functions that accept addresses of // variables as arguments. #include // Function prototypes void getNumber(int *); void doubleValue(int *); void main(void) { int number; getNumber(&number) // Pass address of number to getNumber doubleValue(&number); // and doubleValue. cout << "That value doubled is " << number << endl; }

Starting Out with C++, 3 rd Edition 40 Program continues // Definition of getNumber. The parameter, Input, is a pointer. // This function asks the user for a number. The value entered // is stored in the variable pointed to by Input. void getNumber(int *input) { cout << "Enter an integer number: "; cin >> *input; } // Definition of doubleValue. The parameter, val, is a pointer. // This function multiplies the variable pointed to by val by // two. void doubleValue(int *val) { *val *= 2; }

Starting Out with C++, 3 rd Edition 41 Program Output with Example Input Enter an integer number: 10 [Enter] That value doubled is 20

Starting Out with C++, 3 rd Edition 42 Program 9-12 // This program demonstrates that a pointer may be used as a // parameter to accept the address of an array. Either subscript // or pointer notation may be used. #include // Function prototypes void getSales(float *); float totalSales(float *); void main(void) { float sales[4]; getSales(sales); cout.precision(2);

Starting Out with C++, 3 rd Edition 43 Program continues cout.setf(ios::fixed | ios::showpoint); cout << "The total sales for the year are $"; cout << totalSales(sales) << endl; } // Definition of getSales. This function uses a pointer to accept // the address of an array of four floats. The function asks the // user to enter the sales figures for four quarters, and stores // those figures in the array. (The function uses subscript // notation.) void getSales(float *array) { for (int count = 0; count < 4; count++) { cout << "Enter the sales figure for quarter "; cout << (count + 1) << ": "; cin >> array[count]; }

Starting Out with C++, 3 rd Edition 44 Program continues // Definition of totalSales. This function uses a pointer to // accept the address of an array of four floats. The function // gets the total of the elements in the array and returns that // value. (Pointer notation is used in this function.) float totalSales(float *array) { float sum = 0.0; for (int count = 0; count < 4; count++) { sum += *array; array++; } return sum; }

Starting Out with C++, 3 rd Edition 45 Program Output with Example Input Enter the sales figure for quarter 1: [Enter] Enter the sales figure for quarter 2: [Enter] Enter the sales figure for quarter 3: [Enter] Enter the sales figure for quarter 4: [Enter] The total sales for the year are $

Starting Out with C++, 3 rd Edition Focus on Software Engineering: Dynamic Memory Allocation Variables may be created and destroyed while a program is running. A pointer than contains the address 0 is called a null pointer. Use the new operator to dynamically allocate memory. Use delete to dynamically deallocate memory.

Starting Out with C++, 3 rd Edition 47 Program 9-13 // This program totals and averages the sales figures for any // number of days. The figures are stored in a dynamically // allocated array. #include void main(void) { float *sales, total = 0, average; int numDays; cout << "How many days of sales figures do you wish "; cout << "to process? "; cin >> numDays; sales = new float[numDays]; // Allocate memory

Starting Out with C++, 3 rd Edition 48 Program continues if (sales == NULL) // Test for null pointer { cout << "Error allocating memory!\n"; return; } // Get the sales figures from the user cout << "Enter the sales figures below.\n"; for (int count = 0; count < numDays; count++) { cout << "Day " << (count + 1) << ": "; cin >> sales[count]; } // Calculate the total sales for (count = 0; count < numDays; count++) { total += sales[count]; }

Starting Out with C++, 3 rd Edition 49 Program continues // Calculate the average sales per day average = total / numDays; // Display the results cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "\n\nTotal sales: $" << total << endl; cout << "average sales: $" << average << endl; // Free dynamically allocated memory delete [] sales; }

Starting Out with C++, 3 rd Edition 50 Program Output with Example Input How many days of sales figures do you wish to process? 5 [Enter] Enter the sales figures below. Day 1: [Enter] Day 2: [Enter] Day 3: [Enter] Day 4: [Enter] Day 5: [Enter] total sales: $ average sales: $813.43

Starting Out with C++, 3 rd Edition Focus on Software Engineering: Returning Pointers from Functions Functions can return pointers, but you must be sure the object the pointer references still exists. You should only return a pointer from a function if it is: –A pointer to an object that was passed into the function as an argument. –A pointer to a dynamically allocated object.