Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.

Slides:



Advertisements
Similar presentations
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Pointer Arithmetic Dale Roberts, Lecturer Computer.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Pointers.
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 (Pointers) Lecture 1 –Follow class notes –Some.
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
 2000 Deitel & Associates, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization.
 2006 Pearson Education, Inc. All rights reserved Pointers.
Lecture 7 C Pointers Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
(continue) © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
[S. Uludag] CIS / CSC 175 Problem Solving and Programming I Winter 2010 Suleyman Uludag Department of Computer Science, Engineering and Physics (CSEP)
 2007 Pearson Education, Inc. All rights reserved. 1 C Pointers Chapter 7 from “C How to Program" Another ref:
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Pointers Dale Roberts, Lecturer Computer Science, IUPUI.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C++ Programming Lecture 17 Pointers – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer.
1 Lecture 12 Pointers and Strings Section 5.4, ,
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
1 Chapter 5 - Pointers and Strings Outline 5.1Introduction 5.2Pointer Variable Declarations and Initialization 5.3Pointer Operators 5.4Calling Functions.
 2003 Prentice Hall, Inc. All rights reserved. 1 namespaces Program has identifiers in different scopes –Sometimes scopes overlap, lead to problems Namespace.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Pointers and Strings Outline 5.1 Introduction 5.2 Pointer Variable Declarations and Initialization.
1 Object-Oriented Programming Using C++ A tutorial for pointers.
1 Lecture 8 Pointers and Strings: Part 2 Section 5.4, ,
PGT 106 C Programming POINTERS. PGT 106 C Programming Outline Introduction Pointer Variable Definitions and Initialization Pointer Operators Calling Functions.
1. Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship with arrays and strings 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 7.7Pointer Expressions and Pointer Arithmetic Arithmetic operations can be performed on pointers –Increment/decrement pointer ( ++ or -- ) –Add an integer.
EC-111 Algorithms & Computing Lecture #9 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI N305 Pointers Call-by-Reference.
Lecture 9 - Pointers 1. Outline Introduction Pointer Variable Definitions and Initialization Pointer Operators Calling Functions by Reference Pointer.
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Week 9 - Pointers.
Chapter 7 - Pointers Outline 7.1 Introduction
POINTERS.
EPSII 59:006 Spring 2004.
Chapter 7 - Pointers Outline 7.1 Introduction
Chapter 7 - Pointers Outline 7.1 Introduction
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 7 - Pointers Outline 7.1 Introduction
CSC113: Computer Programming (Theory = 03, Lab = 01)
8 Pointers.
Chapter 7 from “C How to Program"
Pointers and Pointer-Based Strings
Pointers Call-by-Reference CSCI 230
Pointers Kingdom of Saudi Arabia
Chapter 5 - Pointers and Strings
5.1 Introduction Pointers Powerful, but difficult to master
7 C Pointers.
EENG212 ALGORITHMS & DATA STRUCTURES
C++ Programming Lecture 17 Pointers – Part I
POINTERS.
Lecture 2 Arrays & Pointers May 17, 2004
C++ Programming Lecture 18 Pointers – Part II
CISC181 Introduction to Computer Science Dr
Presentation transcript:

Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University

Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer Operators 7.4Calling Functions by Reference 7.5Using the Const Qualifier with Pointers 7.6Bubble Sort Using Call by Reference 7.7Pointer Expressions and Pointer Arithmetic 7.8The Relationship between Pointers and Arrays 7.9Arrays of Pointers 7.10Case Study: A Card Shuffling and Dealing Simulation 7.11Pointers to Functions

7.1Introduction Pointers  Powerful, but difficult to master  Simulate call-by-reference  Create and manipulate dynamic data structures  Close relationship with arrays and strings

7.2Pointer Variable Declarations and Initialization Pointer variables  Contain memory addresses as their values  Normal variables contain a specific value (direct reference)  Pointers contain address of a variable that has a specific value (indirect reference)  Indirection - referencing a pointer value count 7 countPtr count 7

7.2Pointer Variable Declarations and Initialization (II) Pointer declarations  * used with pointer variables int *myPtr;  Declares a pointer to an int (pointer of type int *)  Multiple pointers, multiple * int *myPtr1, *myPtr2;  Can declare pointers to any data type int *myPtr1; float *myPtr2;  Initialize pointers to 0, NULL, or an address 0 or NULL - points to nothing ( NULL is preferred) int 7 myPtr1 float myPtr2

Fig. 7.1 Directly and indirectly referencing a variable count 7 count directly references a variable whose value is 7 count 7 countPtr countPtr indirectly references a variable whose value is 7

Operator precedence

7.3Pointer Operators & (address operator)  Returns address of operand int y = 5; int *yPtr; yPtr = &y; //yPtr gets address of y  yPtr “ points to ” y yPtr y 5 yptr y 5 Address of y is value of yptr

Common Programming Error 7.2 Dereferencing a pointer that has not been initialized or that has not been assigned to point to a specific location in memory. This could cause a fatal execution time error, or it could accidentally modify important data and allow the program to run to completion providing incorrect results. yPtr y 5 yptr y 5 Address of y is value of yptr int y = 5; int *yPtr; yPtr = &y;

7.3Pointer Operators (II) * (indirection/dereferencing operator)  Returns a synonym/alias of what its operand points to *yptr returns y (because yptr points to y )  * can be used for assignment Returns alias to an object *yptr = 7; // changes y to 7  Dereferenced pointer (operand of * ) must be an lvalue (no constants) yPtr y 5 yptr y 5 Address of y is value of yptr int y = 5; int *yPtr; yPtr = &y;

7.3Pointer Operators (III) * and & are inverses  They cancel each other out *&yptr -> * (&yptr) -> * (address of yptr)-> returns alias of what operand points to -> yptr &*yptr -> &(*yptr) -> &(y) -> returns address of y, which is yptr -> yptr yPtr y 5 yptr y 5 Address of y is value of yptr int y = 5; int *yPtr; yPtr = &y;

The address of a is the value of aPtr. The * operator returns an alias to what its operand points to. aPtr points to a, so *aPtr returns a. Notice how * and & are inverses

The address of a is 0012FF7C The value of aPtr is 0012FF7C The value of a is 7 The value of *aPtr is 7 Showing that * and & are complements of each other. &*aPtr = 0012FF7C *&aPtr = 0012FF7C

7.4Calling Functions by Reference Call by reference with pointer arguments  Pass address of argument using & operator  Allows you to change actual location in memory  Arrays are not passed with & because the array name is already a pointer * operator  Used as alias/nickname for variable inside of function void double(int *number) { *number = 2 * (*number); } *number used as nickname for the variable passed

The original value of number is 5 The new value of number is 125

int main() { int number = 5 ; number=cubeByValue(number); } int cubeByValue( int n ) { return n * n * n; } number 5 n Before main calls cubeByValue : undefined int main() { int number = 5; number = cubeByValue( number ); } int cubeByValue(int n ) { return n * n * n; } number 5 n After cubeByValue receives the call: int cubeByValue( int n ) { return n * n * n; } int main() { int number = 5; number = cubeByValue( number ); } number 5 n After cubeByValue cubes parameter n and before cubeByValue returns to main : 5 Fig. 7.8Analysis of a typical call-by-value. (Part 1 of 2.)

125 int main() { int number = 5 ; number = cubeByValue( number ); } int cubeByValue( int n ) { return n * n * n; } number 5 n After cubeByValue returns to main and before assigning the result tonumber : undefined 125 int main() { int number = 5; number = cubeByValue( number ); } int cubeByValue(int n ) { return n * n * n; } number 125 n After main completes the assignment to number : undefined Fig. 7.8Analysis of a typical call-by-value. (Part 2 of 2.)

The original value of number is 5 The new value of number is 125 fig07_07.c Notice how the address of number is given - cubeByReference expects a pointer (an address of a variable). Inside cubeByReference, *nPtr is used (*nPtr is number ). Notice that the function prototype takes a pointer to an integer.

Fig. 7.9Analysis of a typical call-by-reference with a pointer argument. 125 void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; } int main() { int number = 5 ; cubeByReference( &number ); } void cubeByReference( int *nPtr ) { *nPtr = *nPtr * *nPtr * *nPtr; } int main() { int number =5 ; cubeByReference( &number ); } int main() { int number = 5; cubeByReference( &number ); } number 5 nPtr number 5 nPtr number 125 nPtr Before main calls cubeByReference : After cubeByReference receives the call and before * nPtr is cubed: After * nPtr is cubed and before program control returns to main: undefined call establishes this pointer called function modifies caller’s variable

7.5Using the Const Qualifier with Pointers const qualifier - variable cannot be changed  Good idea to have const if function does not need to change a variable  Attempting to change a const is a compiler error const pointers - point to same memory location  Must be initialized when declared int *const myPtr = &x; Type int *const - constant pointer to an int const int *myPtr = &x; Regular pointer to a const int const int *const Ptr = &x; const pointer to a const int x can be changed, but not *Ptr

Compiling... FIG07_13.c D:\books\2003\chtp4\Examples\ch07\FIG07_13.c(15) : error C2166: l-value specifies­ const object Error executing cl.exe. FIG07_13.exe - 1 error(s), 0 warning(s) Changing *ptr is allowed – x is not a constant. Changing ptr is an error – ptr is a constant pointer.

Compiling... FIG07_14.c D:\books\2003\chtp4\Examples\ch07\FIG07_14.c(17) : error C2166: l-value specifies­ const object D:\books\2003\chtp4\Examples\ch07\FIG07_14.c(18) : error C2166: l-value specifies­ const object Error executing cl.exe. FIG07_12.exe - 2 error(s), 0 warning(s)

7.6Bubble Sort Using Call-by-reference Implement bubblesort using pointers  Swap two elements  swap function must receive address (using &) of array elements Array elements have call-by-value default  Using pointers and the * operator, swap can switch array elements Psuedocode Initialize array print data in original order Call function bubblesort print sorted array Define bubblesort

7.6Bubble Sort Using Call-by-reference (II) sizeof  To determine the size in bytes of an array  For arrays: size of 1 element * number of elements  if sizeof(int) = 4 bytes, then int myArray[10]; printf( "%d", sizeof( myArray ) ); will print 40 sizeof can be used with  Variable names  Type name  Constant values

Example of sizeof To determine the number of elements in the array double real[22]; sizeof (real) / sizeof (double) /* size_t is defined in stdio.h */ size_t getSize ( float * ) size_t getsize ( float *ptr) { reutrn sizeof (ptr); }

Bubblesort gets passed the address of array elements (pointers). The name of an array is a pointer.

Data items in original order Data items in ascending order

7.7Pointer Expressions and Pointer Arithmetic Arithmetic operations can be performed on pointers  Increment/decrement pointer ( ++ or -- )  An integer may be added (subtracted) to a pointer( + or +=, - or -= )  Pointers may be subtracted from each other  Operations meaningless unless performed on an array

7.7Pointer Expressions and Pointer Arithmetic (II) int v[10], *vPtr; /* declare a v array and a pointer variable */ 5 element int array on machine with 4 byte int s  vPtr points to first element v[0] vPtr = v; at location ( vPtr = 3000 ) or vPtr = & v[0]  vPtr +=2; /* sets vPtr to 3008 = *4 */ vPtr points to v[2] (incremented by 2), but machine has 4 byte int s. pointer variable vPtr v[0]v[1]v[2]v[4]v[3] location

7.7Pointer Expressions and Pointer Arithmetic (III) Subtracting pointers  Returns number of array elements from one to the other.  int *vPtr2, *vptr; vPtr2 = &v[2]; vPtr = &v[0]; x = vPtr2 – vPtr; /* x is equal to 2 */ Pointer comparison ( )  See which pointer points to the higher numbered array element  Also, see if a pointer points to 0 pointer variable vPtr v[0]v[1]v[2]v[4]v[3] location

7.7Pointer Expressions and Pointer Arithmetic (IV) Pointers of the same type can be assigned to each other  If not the same type, a cast operator must be used  Exception: pointer to void (type void * ) Generic pointer, represents any type No casting needed to convert a pointer to void pointer void pointers cannot be dereferenced

7.8The Relationship Between Pointers and Arrays Arrays and pointers closely related  Array name like a constant pointer  Pointers can do array subscripting operations Declare an array b[5] and a pointer variable bPtr (int *bPtr;) bPtr = b; Array name actually a address of first element OR bPtr = &b[0]; Explicitly assign bPtr to address of first element

7.8The Relationship Between Pointers and Arrays (II) Element b[n]  can be accessed by *( bPtr + n )  n - offset (pointer/offset notation)  The address &b[3] can be written with the pointer expression bPtr + 3  The array itself can be treated as a pointer b[3] same as *(b + 3)  Pointers can be subscripted (pointer/subscript notation) bPtr[3] same as b[3]

Array b printed with: Array subscript notation b[ 0 ] = 10 b[ 1 ] = 20 b[ 2 ] = 30 b[ 3 ] = 40 Pointer/offset notation where the pointer is the array name *( b + 0 ) = 10 *( b + 1 ) = 20 *( b + 2 ) = 30 *( b + 3 ) = 40 Pointer subscript notation bPtr[ 0 ] = 10 bPtr[ 1 ] = 20 bPtr[ 2 ] = 30 bPtr[ 3 ] = 40 Pointer/offset notation *( bPtr + 0 ) = 10 *( bPtr + 1 ) = 20 *( bPtr + 2 ) = 30 *( bPtr + 3 ) = 40

An array name is essentially a constant pointer; it always points to the beginning of the array. Thus, the expression b += 3 is invalid.

String literal A string is a one-dimensional char array. pointer variable string2 ‘H’‘e’‘l’‘o’‘l’ location ‘\0’ 3005 Literal Pool

string1 = Hello string3 = Good Bye

7.9Arrays of Pointers Arrays can contain pointers - array of strings char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades" };  String: pointer to first character  char * - each element of suit is a pointer to a char  Strings not actually in array - only pointers to string in array suit array has a fixed size, but strings can be of any size. suit[3] suit[2] suit[1] suit[0]’H’’e’’a’’r’’t’’s’ ’\0’ ’D’’i’’a’’m’’o’’n’’d’’s’ ’\0’ ’C’’l’’u’’b’’s’ ’\0’ ’S’’p’’a’’d’’e’’s’ ’\0’

7.11Pointers to Functions Pointer to function  Contains address of function  Similar to how array name is address of first element  Function name is starting address of code that defines function Function pointers can be  Passed to functions  Stored in arrays  Assigned to other function pointers

7.11 Pointers to Functions (II) Example: bubblesort  Function bubble takes a function pointer bubble calls this helper function this determines ascending or descending sorting  The argument in bubblesort for the function pointer: bool ( *compare )( int, int ) tells bubblesort to expect a pointer to a function that takes two int s and returns a bool.  If the parentheses were left out: bool *compare( int, int ) Declares a function that receives two integers and returns a pointer to a bool

Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 1 Data items in original order Data items in ascending order Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 2 Data items in original order Data items in descending order