C++ Programming Chapter 7 Pointers

Similar documents
by Pearson Education, Inc. All Rights Reserved.

Lecture 05 POINTERS 1

Fundamentals of Programming Session 20

Programming for Engineers Pointers

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

Chapter 6 - Pointers

MYcsvtu Notes LECTURE 34. POINTERS

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers and Strings Prentice Hall, Inc. All rights reserved.

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

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

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

CSC 211 Intermediate Programming. Arrays & Pointers

Relationship between Pointers and Arrays

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

IS 0020 Program Design and Software Tools

C Pointers Pearson Education, Inc. All rights reserved.

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

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Lecture 4. Default Arguments. Set defaults in function prototype. int myfunction( int x = 1, int y = 2, int z = 3 );

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Lecture 9 - Pointers 1

Pointers and Strings. Adhi Harmoko S, M.Komp

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

CSC 211 Intermediate Programming. Pointers

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Chapter 7 C Pointers

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

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

C++ for Java Programmers

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Review of the C Programming Language for Principles of Operating Systems

Fundamentals of Programming Session 20

What is an algorithm?

Introduction to Computer Science Midterm 3 Fall, Points

CS2141 Software Development using C/C++ C++ Basics

Review of the C Programming Language

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

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

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

Pointers. 10/5/07 Pointers 1

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

UNIT- 3 Introduction to C++

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

Content. In this chapter, you will learn:

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Homework #3 CS2255 Fall 2012

Functions. Introduction :

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

OBJECT ORIENTED PROGRAMMING

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

C++ Programming: From Problem Analysis to Program Design, Third Edition

Objectives. In this chapter, you will:

[0569] p 0318 garbage

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Ch. 12: Operator Overloading

Week 3: Pointers (Part 2)

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

egrapher Language Reference Manual

CSCI-1200 Data Structures Spring 2014 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Tokens, Expressions and Control Structures

Pointers in C/C++ 1 Memory Addresses 2

Review of Important Topics in CS1600. Functions Arrays C-strings

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary


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

Pointers. Pointer References

Introduction to C++ Introduction to C++ 1

PROGRAMMAZIONE I A.A. 2017/2018

C++ PROGRAMMING SKILLS Part 4: Arrays

Fundamental of Programming (C)

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

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

CSCI 171 Chapter Outlines

Pointers. Reference operator (&) ted = &andy;

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

UNIT-2 Introduction to C++

Pointers as Arguments

by Pearson Education, Inc. All Rights Reserved. 2

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

Exam 3 Chapters 7 & 9

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):

CS201 Some Important Definitions

BITG 1113: POINTER LECTURE 12

Reference operator (&)

Reserved Words and Identifiers

Transcription:

C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department of Electrical Engineering National Taiwan University Objectives Pointers also enable pass-by-reference and can be used to create and manipulate dynamic data structures that can grow and shrink, such as linked lists, queues, stacks and trees. 2

Contents 3 7.2 Pointer Variable Declarations and Initialization A pointer contains the memory address of a variable that, in turn, contains a specific value. In this sense, a variable name directly references a value, and a pointer indirectly references a value. Referencing a value through a pointer is called indirection. Diagrams typically represent a pointer as an arrow from the variable that contains an address to the variable located at that address in memory. 4

7.2 Pointer Variable Declarations and Initialization The declaration int *countptr, count; declares the variable countptr to be of type int * (i.e., a pointer to an int value) and is read (right to left), countptr is a pointer to int. count is declared to be an int, not a pointer The * in the declaration applies only to countptr. A variable being declared as a pointer must be preceded by an asterisk (*). When * appears in a declaration, it isn t an operator; rather, it indicates that the variable being declared is a pointer. Pointers can be declared to point to objects of any data type. 5 7.2 Pointer Variable Declarations and Initialization Pointers should be initialized either when they re declared or in an assignment. A pointer may be initialized to 0, NULL or an address of the corresponding type. A pointer with the value 0 or NULL points to nothing and is known as a null pointer. NULL is equivalent to 0, but in C++, 0 is used by convention. The value 0 is the only integer value that can be assigned directly to a pointer variable without first casting the integer to a pointer type. 6

7.2 Pointer Variable Declarations and Initialization 7 7.3 Pointer Operators The address operator (&) is a unary operator that obtains the memory address of its operand. Assuming the declarations int y = 5; // declare variable y int *yptr; // declare pointer variable yptr the statement yptr = &y; // assign address of y to yptr assigns the address of the variable y to pointer variable yptr. A pointer representation in memory with integer variable y stored at memory location 600000 and pointer variable yptr stored at memory location 500000. 8

7.3 Pointer Operators The operand of the address operator must be an lvalue; the address operator cannot be applied to constants or to expressions that do not result in references. The * operator, commonly referred to as the indirection operator or dereferencing operator, returns a synonym for the object to which its pointer operand points. Called dereferencing a pointer A dereferenced pointer may also be used on the left side of an assignment. The & and * operators are inverses of one another. 9 10

7.3 Pointer Operators 11 7.3 Pointer Operators 12

7.4 Pass-by-Reference with Pointers Three ways in C++ to pass arguments to a function pass-by-value pass-by-reference with reference arguments pass-by-reference with pointer arguments Pointers, like references, can be used to modify one or more variables in the caller or to pass pointers to large data objects to avoid the overhead of passing the objects by value. In C++, you can use pointers and the indirection operator (*) to accomplish pass-by-reference. When calling a function with an argument that should be modified, the address of the argument is passed. When the address of a variable is passed to a function, the indirection operator (*) can be used in the function to form a synonym for the name of the variable (i.e., an lvalue) used to modify the variable s value at that location in the caller s memory. 13 14

15 7.4 Pass-by-Reference with Pointers The compiler does not differentiate between a function that receives a pointer and a function that receives a one-dimensional (1D) array. In the function header and in the prototype for a function that expects a 1D array as an argument, pointer notation may be used. When the compiler encounters a function parameter for a onedimensional array of the form int b[], the compiler converts the parameter to the pointer notation int *b. Both forms are interchangeable. 16

7.5 Using const with Pointers Principle of least privilege - Always give a function enough access to the data in its parameters to accomplish its specified task, but no more. Four ways to pass a pointer to a function a nonconstant pointer to nonconstant data (max. access privilege) The data can be modified through the dereferenced pointer, and the pointer can be modified to point to other data. E.g. int *countptr; a nonconstant pointer to constant data a constant pointer to nonconstant data a constant pointer to constant data (minimum access privilege) 17 7.5 Using const with Pointers (N+C) A nonconstant pointer to constant data a pointer that can be modified to point to any data item of the appropriate type but the data to which it points cannot be modified through that pointer e.g. used to receive an array argument to a function that will process each array element, but should not be allowed to modify the data. const int *countptr; any attempt to modify the data in the function => compilation error. 18

19 7.5 Using const with Pointers (C+N) A constant pointer to nonconstant data a pointer that always points to the same memory location the data at that location can be modified through the pointer e.g. an array name, a constant pointer to the beginning of the array all data in the array can be accessed and changed constant pointers must be initialized when they re declared can be used to receive an array as an argument to a function it s initialized with a pointer that s passed to the function. 20

21 7.5 Using const with Pointers (C+C) Constant pointer to constant data (minimum access privilege) such a pointer always points to the same memory location the data at that location cannot be modified via the pointer e.g. an array passed to a function - only read, no modification 22

7.6 Selection Sort Using Pass-by-Reference Easy-to-program, but inefficient, sorting algorithm. After the ith iteration, the smallest i items of the array will be sorted into increasing order in the first i elements of the array. 1st iteration: selects the smallest element, swaps it with the 1 st element 2 nd iteration: selects the 2 nd -smallest element (the smallest element of the remaining elements), swaps it with the second element until the last iteration: selects the 2 nd -largest element, swaps it 23 24

selectionsort wants swap to have access to the array elements to be swapped => selectionsort passes each of these elements to swap by reference 25 7.7 sizeof Operator sizeof: a unary operator determines the size of an array (or of any other data type, variable or constant) in bytes during program compilation When applied to the name of an array => returns the total number of bytes in the array as a value of type size_t. When applied to a pointer parameter in a function that receives an array as an argument => returns the size of the pointer in bytes not the size of the array. Get the number of elements double realarray[ 22 ]; int numberofelement = sizeof realarray / sizeof( realarray[ 0 ] ); 26

27 28

Applied to a variable name (not an array name) or other expression the number of bytes used to store the specific type of the expression s value is returned type name: the parentheses required sizeof in MSDN: http://msdn.microsoft.com/en-us/library/4s7x1k91(v=vs.71).aspx 29 7.7 sizeof Operator 30

7.8 Pointer Expressions and Pointer Arithmetic Pointers are valid operands in arithmetic expressions, assignment expressions and comparison expressions. pointer arithmetic certain arithmetic operations may be performed on pointers: increment (++) and decremented (--) an integer may be added/substracted to a pointer (+ or += / - or -=) one pointer may be subtracted from another of the same type 31 7.8 Pointer Expressions and Pointer Arithmetic In conventional arithmetic, 3000 + 2 =>3002 Normally not the case with pointer arithmetic. int v[5]; vptr +=2; // or vptr =vptr + 2; vptr = vptr + 2* sizeof(data type) vptr += 2; by that integer times the size of the object to which the pointer refers. The number of bytes depends on the object s data type. 32

7.8 Pointer Expressions and Pointer Arithmetic Pointer variables pointing to the same array may be subtracted from one another. Pointer arithmetic is meaningless unless performed on a pointer that points to an array. Ex., vptr = 3000 and v2ptr = 3008, the statement x = v2ptr - vptr; would assign to x the number of array elements from vptr to v2ptr. A pointer can be assigned to another pointer if both pointers are of the same type. All pointer types can be assigned to a pointer of type void * without casting. 33 7.8 Pointer Expressions and Pointer Arithmetic Otherwise, a cast operator (reinterpret_cast in Section 17.8) must be used to convert 34

7.8 Pointer Expressions and Pointer Arithmetic A void * pointer cannot be dereferenced. The compiler must know the data type to determine the number of bytes to be dereferenced for a particular pointer for a pointer to void, this number of bytes cannot be determined from the type. Pointers can be compared using equality and relational operators. Comparisons using relational operators are meaningless unless the pointers point to members of the same array. Pointer comparisons compare the addresses stored in the pointers. A common use of pointer comparison is determining whether a pointer is 0 (i.e., the pointer is a null pointer it does not point to anything). 35 7.9 Relationship Between Pointers and Arrays An array name can be thought of as a constant pointer. Pointers can be used to do any operation involving array subscripting. Assume the following declarations: int b[ 5 ]; // create 5-element int array b int *bptr; // create int pointer bptr Because the array name (without a subscript) is a (constant) pointer to the first element of the array, we can bptr = b; // assign address of array b to bptr equivalent to bptr = &b[ 0 ]; // also assigns address of // array b to bptr Pointer/offset notation Alternatively, array element b[ 3 ] be referenced with *( bptr + 3 ) // 3: offset to the pointer The parentheses are necessary, because the precedence of * is higher than that of +. 36

7.9 Relationship Between Pointers and Arrays The address &b[ 3 ] can be written with bptr + 3 The array name (which is implicitly const) can be treated as a pointer and used in pointer arithmetic. In general, all subscripted array expressions can be written with a pointer and an offset. The expression *( b + 3 ) also refers to the array element b[ 3 ] pointer/subscript notation Pointers can be subscripted exactly as arrays can. the expression bptr[ 1 ] refers to the array element b[ 1 ] 37 38

39 7.10 Pointer-Based String Processing C-style, pointer-based strings C++ s string class is preferred for use in new programs, because it eliminates many of the security problems that can be caused by manipulating C strings. Character constant The value of a character constant is the integer value of the character in the machine s character set. A string is a series of characters treated as a single unit. May include letters, digits and various special characters such as +, -, *, /and $. String literals, or string constants, in C++ are written in double quotation marks e.g. Yih-Peng Chiou BL617, Electrical Dept. A pointer-based string is an array of characters ending with a null character ('\0'). A string is accessed via a pointer to its first character. The value of a string literal is the address of its first character, but the sizeof a string literal is the length of the string including the terminating null character. 40

7.10 Pointer-Based String Processing Initializer in the declaration char color[] = blue ; char color[] = { b, l, u, e, \0 }; String literals have static storage class The effect modifying a string literal is undefined; thus, you should always declare a pointer to a string literal as const char *. const char * colorptr = blue ; When declaring a character array to contain a string, the array must be large enough to store the string and its terminating null character. Access individual characters in a string directly with array subscript notation u is color[2] 41 7.10 Pointer-Based String Processing cin: reads characters until a white space or end-of-file indictor cin >> setw(20) >> word; Read max. 19 characters (and \0 ) in array word 42

7.10 Pointer-Based String Processing Member function cin.getline char sentence[80]; cin.getline(sentence, 80, \n ); cin.getline(char array, length, delimiter char ); read until 3 rd parameter ( \n is default) cin.getline(sentence, 80); cout << sentence; output until the null character \0, \0 is not printed cin and cout assume that character arrays should be processed as strings terminated by null characters; no similar input and output processing capabilities for other array types. 43 7.10 Pointer-Based String Processing 44

7.11 Arrays of Pointers Arrays may contain pointers. string array: an array of pointer-based string. Each entry in the array is a string, but in C++ a string is essentially a pointer to its first character, so each entry in an array of strings is simply a pointer to the first character of a string. const char * const suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; An array of four elements. Each element is of type pointer to char constant data. 45 7.11 Arrays of Pointers Can be stored in 2D array, but inefficient due to fixed number of column (must large enough for the largest) String arrays are commonly used with command-line arguments that are passed to function main when a program begins execution. int main(int argc, char* argv[]) Such arguments follow the program name when a program is executed from the command line. A typical use of command-line arguments is to pass options to a program. 46

7.12 Function Pointers A pointer to a function contains the function s address in memory. A function s name is actually the starting address in memory of the code that performs the function s task. Pointers to functions can be Passed to functions Returned from functions Stored in arrays Assigned to other function pointers Used to call the underlying function Function selectionsort receives a pointer to a function either function ascending or function descending as an argument in addition to the integer array to sort and the size of the array. Functions ascending and descending determine the sorting order. 47 48

49 50

bool ( *compare )( int, int ) This parameter specifies a pointer to a function. The text (*compare) indicates the name of the pointer to the function (the * indicates that parameter compare is a pointer). Parentheses are needed around *compare to indicate that compare is a pointer to a function. 51 bool ( *compare )( int, int ) The corresponding parameter in the function prototype of selectionsort is bool (*)( int, int ) The function passed to selectionsort is called as follows: ( *compare )( work[ smallestorlargest ], work[ index ] ) Just as a pointer to a variable is dereferenced to access the value of the variable, a pointer to a function is dereferenced to execute the function. The parentheses around *compare are necessary; otherwise, the * operator would attempt to dereference the value returned from the function call. Call could have been made without dereferencing the pointer, as in compare( work[ smallestorlargest ], work[ index ] ) which uses the pointer directly as the function name. 52