Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

Similar documents
Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

What is an algorithm?

Pointers! Arizona State University 1

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Exam 3 Chapters 7 & 9

Homework #3 CS2255 Fall 2012

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Pointers and Dynamic Memory Allocation

Variables, Memory and Pointers

Structured Data. CIS 15 : Spring 2007

Pointers. Variable Declaration. Chapter 10

Pointers. Memory. void foo() { }//return

a data type is Types

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

Pointers, Dynamic Data, and Reference Types

Pointers in C/C++ 1 Memory Addresses 2

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

Lecture 23: Pointer Arithmetic

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Pointers. Developed By Ms. K.M.Sanghavi

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

Week 3: Pointers (Part 2)

pointers + memory double x; string a; int x; main overhead int y; main overhead

CMSC202 Computer Science II for Majors

CSC 1300 Exam 4 Comprehensive-ish and Structs

C++ for Java Programmers

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Pointers II. Class 31

FORM 2 (Please put your name and form # on the scantron!!!!)

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

CS31 Discussion 1E Spring 17 : week 08

Pointers. 10/5/07 Pointers 1

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

MEMORY ADDRESS _ REPRESENTATION OF BYTES AND ITS ADDRESSES

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

C Pointers. 6th April 2017 Giulio Picierro

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 161 Exam II Winter 2018 FORM 1

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

BITG 1113: POINTER LECTURE 12

True or False (15 Points)

Practice question Answers

Programming in C/C Lecture 2

CS2255 HOMEWORK #1 Fall 2012

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Array Elements as Function Parameters

FUNCTIONS POINTERS. Pointers. Functions

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

Dynamic Memory Allocation

Chapter 1: Object-Oriented Programming Using C++

1. Which of the following best describes the situation after Line 1 has been executed?

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Pointers. Lecture 1 Sections Robb T. Koether. Hampden-Sydney College. Wed, Jan 14, 2015

SYSC 2006 C Winter 2012

Functions, Arrays & Structs

Language comparison. C has pointers. Java has references. C++ has pointers and references

12. Pointers Address-of operator (&)

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Pointers and References

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Week 8. Muhao Chen

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Dynamic Allocation of Memory

Chapter 7 C Pointers


C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Computer Programming Lecture 12 Pointers

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

CSC 211 Intermediate Programming. Arrays & Pointers

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

04-17 Discussion Notes

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Lecture on pointers, references, and arrays and vectors

04-19 Discussion Notes

CS 103 Unit 11. Linked Lists. Mark Redekopp


Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

C++ Programming Chapter 7 Pointers

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CSE 333 Midterm Exam July 24, Name UW ID#

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Fri, Jan 18, 2013

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Arrays and Pointers in C. Alan L. Cox

Pointers and Arrays. Introduction To Pointers. Using The "Address Of" The Operator & Operator. Using The Dereference. The Operator * Operator

Transcription:

Chapter 9: Pointers 9.1 Getting the Address of a Variable Getting the Address of a Variable Each variable in program is stored at a unique address Use address operator & to get address of a variable: int num = -99; cout << &num; // prints address // in hexadecimal 9.2 Pointer variable : Often just called a pointer, it's a variable that holds an address Because a pointer variable holds the address of another piece of data, it "points" to the data Something Like Pointers: Arrays We have already worked with something similar to pointers, when we learned to pass arrays as arguments to functions. For example, suppose we use this statement to pass the array numbers to the showvalues function: showvalues(numbers, SIZE); 1

Something Like Pointers : Arrays C++ automatically stores the address of numbers in the values parameter. The values parameter, in the showvalues function, points to the numbers array. Something Like Pointers: Reference Variables We have also worked with something like pointers when we learned to use reference variables. Suppose we have this function: void getorder(int &donuts) { cout << "How many doughnuts do you want? "; cin >> donuts; } And we call it with this code: int jellydonuts; getorder(jellydonuts); Something Like Pointers: Reference Variables The donuts parameter, in the getorder function, points to the jellydonuts variable. Pointer variables are yet another way using a memory address to work with a piece of data. Pointers are more "low-level" than arrays and reference variables. C++ automatically stores the address of jellydonuts in the donuts parameter. This means you are responsible for finding the address you want to store in the pointer and correctly using it. Definition: int *intptr; Read as: intptr can hold the address of an int Spacing in definition does not matter: int * intptr; // same as above int* intptr; // same as above Assigning an address to a pointer variable: int *intptr; intptr = &num; Memory layout: address of num: 0x4a00 num intptr 25 0x4a00 2

A Pointer Variable in Program 9-2 Initialize pointer variables with the special value nullptr. In C++ 11, the nullptr key word was introduced to represent the address 0. Here is an example of how you define a pointer variable and initialize it with the value nullptr: int *ptr = nullptr; The Indirection Operator The Indirection Operator in Program 9-3 The indirection operator (*) dereferences a pointer. It allows you to access the item that the pointer points to. int x = 25; int *intptr = &x; cout << *intptr << endl; This prints 25. The Indirection Operator in Program 9-3 9.3 The Relationship Between Arrays and Pointers 3

The Relationship Between Arrays and Pointers Array name is starting address of array int vals[] = {4, 7, 11}; starting address of vals: 0x4a00 cout << vals; 4 7 11 // displays // 0x4a00 cout << vals[0]; // displays 4 The Relationship Between Arrays and Pointers Array name can be used as a pointer constant: int vals[] = {4, 7, 11}; cout << *vals; // displays 4 Pointer can be used as an array name: int *valptr = vals; cout << valptr[1]; // displays 7 The Array Name Being Dereferenced in Program 9-5 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 ( ) as shown in the expressions Array Access Array elements can be accessed in many ways: Array access method Example array name and [] vals[2] = 17; pointer to array and [] valptr[2] = 17; array name and subscript arithmetic pointer to array and subscript arithmetic *(vals + 2) = 17; *(valptr + 2) = 17; Array Access Conversion: vals[i] is equivalent to *(vals + i) No bounds checking performed on array access, whether using array name or a pointer 4

From Program 9-7 9.4 Pointer Arithmetic Pointer Arithmetic From Program 9-9 Operations on pointer variables: Operation Example 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 9.5 Initializing Pointers Can initialize at definition time: int num, *numptr = &num; int val[3], *valptr = val; Cannot mix data types: double cost; int *ptr = &cost; // won t work Can test for an invalid address for ptr with: if (!ptr)... 5

Comparing Pointers 9.6 Comparing Pointers Relational operators (<, >=, etc.) can be used to compare addresses in pointers Comparing addresses in pointers is not the same as comparing contents pointed at by pointers: if (ptr1 == ptr2) // compares // addresses if (*ptr1 == *ptr2) // compares // contents Pointers as Function Parameters 9.7 Pointers as Function Parameters A pointer can be a 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 Example Pointers as Function Parameters in Program 9-11 void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } int num1 = 2, num2 = -3; swap(&num1, &num2); (Program Continues) 6

Pointers as Function Parameters in Program 9-11 Pointers to Constants If we want to store the address of a constant in a pointer, then we need to store it in a pointer-to-const. Pointers to Constants Pointers to Constants Example: Suppose we have the following definitions: const int SIZE = 6; const double payrates[size] = { 18.55, 17.45, 12.85, 14.97, 10.35, 18.89 }; In this code, payrates is an array of constant doubles. Suppose we wish to pass the payrates array to a function? Here's an example of how we can do it. void displaypayrates(const double *rates, int size) { for (int count = 0; count < size; count++) { cout << "Pay rate for employee " << (count + 1) << " is $" << *(rates + count) << endl; } } The parameter, rates, is a pointer to const double. Declaration of a Pointer to Constant Constant Pointers A constant pointer is a pointer that is initialized with an address, and cannot point to anything else. Example int value = 22; int * const ptr = &value; 7

Constant Pointers Constant Pointers to Constants A constant pointer to a constant is: a pointer that points to a constant a pointer that cannot point to anything except what it is pointing to Example: int value = 22; const int * const ptr = &value; Constant Pointers to Constants 9.8 Dynamic Memory Allocation Dynamic Memory Allocation Can allocate storage for a variable while program is running Computer returns address of newly allocated variable Uses new operator to allocate memory: double *dptr = nullptr; dptr = new double; new returns address of memory location Dynamic Memory Allocation Can also use new to allocate array: const int SIZE = 25; arrayptr = new double[size]; Can then use [] or pointer arithmetic to access array: for(i = 0; i < SIZE; i++) *arrayptr[i] = i * i; or for(i = 0; i < SIZE; i++) *(arrayptr + i) = i * i; Program will terminate if not enough memory available to allocate 8

Releasing Dynamic Memory Dynamic Memory Allocation in Program 9-14 Use delete to free dynamic memory: delete fptr; Use [] to free dynamic array: delete [] arrayptr; Only use delete with dynamic memory! Dynamic Memory Allocation in Program 9-14 Dynamic Memory Allocation in Program 9-14 Program 9-14 (Continued) Program 9-14 (Continued) Notice that in line 49 nullptr is assigned to the sales pointer. The delete operator is designed to have no effect when used on a null pointer. 9.9 Returning Pointers from Functions Returning Pointers from Functions Pointer can be the return type of a function: int* newnum(); The function must not return a pointer to a local variable in the function. A function should only return a pointer: to data that was passed to the function as an argument, or to dynamically allocated memory 9

From Program 9-15 9.10 Using Smart Pointers to Avoid Memory Leaks Using Smart Pointers to Avoid Memory Leaks In C++ 11, you can use smart pointers to dynamically allocate memory and not worry about deleting the memory when you are finished using it. Three types of smart pointer: unique_ptr shared_ptr weak_ptr Must #include the memory header file: #include <memory> In this book, we introduce unique_ptr: unique_ptr<int> ptr( new int ); Using Smart Pointers to Avoid Memory Leaks The notation <int> indicates that the pointer can point to an int. The name of the pointer is ptr. The expression new int allocates a chunk of memory to hold an int. The address of the chunk of memory will be assigned to ptr. Using Smart Pointers in Program 9-17 10