Copyright 2001 Oxford Consulting, Ltd1 January 2001 - 1 - Pointers and More Pointers Pointers and Arrays We’ve now looked at  Pointers  Arrays  Strings.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
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.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Chapter 9: Arrays and Strings
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Adapted from Dr. Craig Chase, The University of Texas at Austin.
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.
Pointers Applications
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Microsoft Visual C++.NET Chapter 61 Memory Management.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
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.
Integer Types short month; // half of a machine word int car; // one machine word unsigned long distance; Character Types char c = ‘\0’; // one byte char.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
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.
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.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Pointers. What Is Pointer l every variable has memory address char c=’y’; int i=2; address of variable i is 0022 l address can used to refer to this variable.
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.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Motivation and Overview
Pointers.
Pointers and Memory Overview
Student Book An Introduction
Lecture 6 C++ Programming
Pointers and References
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays We’ve now looked at  Pointers  Arrays  Strings Let’s now see how all these tie together Also look at advanced pointer concepts

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Let’s begin with look at the relationship between pointers and arrays Recall that an array is collection of values of a single data type

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Consider an array of ints, a [ ], stored in memory By definition, the value of a variable of type array Is the address of the 0th element For our array, the following are equivalent &a [ 0 ] a Thus, If a [ ] is loaded at address 3000 Then &a[0] = a = 3000

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Such an equivalence allows us to write A bit more surprising is a [ j ] is equivalent to *(a + j) Should not be….let’s see why int a[10]; // declare an array of 10 ints int *pa; // declare a pointer to an int pa = a; // assign the address of a[ ] to the pointer int a[10]; // declare an array of 10 ints int *pa; // declare a pointer to an int pa = a; // assign the address of a[ ] to the pointer

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays We know a + j is the address of the jth element beyond a We have also seen a [ j ] = a + j * sizeof (an element of a) We have several ways of addressing an array int a[ ] = {1, 2, 3, 4, 5}; int *pa = a; a[ i ] *(pa + i) *pa++ (*pa)++ // which increments the contents We have several ways of addressing an array int a[ ] = {1, 2, 3, 4, 5}; int *pa = a; a[ i ] *(pa + i) *pa++ (*pa)++ // which increments the contents

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Multi Dimensional Arrays We’ve been looking at arrays in one dimension It’s Possible to declare multiple dimensional arrays Our arrays have had one column and multiple rows We can extend these by simply adding more columns It all reduces to managing pointers We’ll start with 2 dimensions Then briefly explore larger arrays

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Multi Dimensional Arrays Let’s go back to the basics We know an array is collection of values Single data type is represented as Then stored in memory as

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Multi Dimensional Arrays Array can be specified such that the elements are objects of any type including pointers or addresses If a single dimensional array contains pointers to other arrays, we can easily build up a two dimensional array We specify array by its number of Rows Columns An array’s dimension refers to the number of columns

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Arrays The simplest complex array is two dimensional Its elements are one dimensional arrays syntax: type arrayName [ rowSize ] [ columnSize ] syntax: type arrayName [ rowSize ] [ columnSize ]

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Arrays We can write int year [12][31] The declaration says that year is Array of 12 elements Which we can use to express the months Array of 31 ints Which we can use to express the days of the month

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Arrays For two dimensional array, we can access a particular element by specifying the row and column To To get the 7th month and 13th day….. ….We write year[7][13] As expected….. First index identifies the row Second index specifies column in that row

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Array Implementation Two dimensional arrays are implemented as an array of pointers to arrays b[m][n] They are stored as an array of m pointers to arrays with n elements each Elements of each constituent array are stored in adjacent memory locations

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Array Implementation

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Array Implementation Two dimensional array differ from simple array of pointers to arrays  The declaration of two dimensional array Initializes the main array to point to component arrays All component arrays are same size  Array of pointers Must be initialized by programmer  All component arrays may be different sizes Sometimes referred to as a ragged array

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Array Implementation For array a[2] [3], the elements stored as a[0][0], a[0][1], a[0][2], a[1[0], a[1[1], a[1][2] Element a[1][2] is addressed as: *(*(a + 1) + 2) 1. a is 2 by 3 array. It points to first element of a 3 element subarray 2. a + 1 points to the second 3 element subarray 3. *(a + 1) points to the first element of the second 3 element subarray 4. *(a + 1) + 2 points to the third element of the second subarray 5. *(*(a + 1) + 2) is third element in second subarray 1. a is 2 by 3 array. It points to first element of a 3 element subarray 2. a + 1 points to the second 3 element subarray 3. *(a + 1) points to the first element of the second 3 element subarray 4. *(a + 1) + 2 points to the third element of the second subarray 5. *(*(a + 1) + 2) is third element in second subarray

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Two Dimensional Array Implementation In general a two-dimensional arrays are accessed by  Array notation or  Pointer notation  Array notation is used when dealing with the array itself and  Pointer notation is used when all you have is the address of the array The address of any element in our example array is guaranteed to be (a + 3*i + j)

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Dynamic Allocation of Two Dimensional Arrays Two-dimensional arrays can be allocated on the heap with the new operator with following syntax: The allocation defines x as a pointer to i arrays of j elements int (* x)[j] = new int[i][j];

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Deleting Two Dimensional Arrays When dynamically allocated two-dimensional arrays are deleted….. ….The delete operator requires only one [ ] regardless of the number of dimensions in the array delete [] x;//Correct. delete [][] x;//Error. Use only one []

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Multidimensional Dimensional Arrays C and C++ place no restriction on the number of dimensions an array may have Multidimensional arrays are stored in row major order Elements differing only in last subscript are stored adjacently

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Multidimensional Dimensional Arrays Pointer conversion and addressing done as in two dimensional arrays only in more dimensions In General an expression of form…. i by j by k ….is converted to the form pointer to j by k

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Multidimensional Dimensional Arrays The mechanics of the two-dimensional arrays can be extended to cover arrays with more dimensions... For following 3 dimensional array int a[2][3][4]; The address of an element (&a[i][j][k]) Is guaranteed to be (array + 2*3*i + 3*j + k)

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Generic and Null Pointers The pointers we’ve dealt with point to a variable of a particular type Often we would like to use same pointer to point to a variable of any data type In C++ will see this is a simple form of polymorphism ANSI C++ introduces the generic pointer

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Generic Pointers The generic pointer is a pointer to type void void * void * pointer guaranteed to be large enough to hold pointer to any type of object except a function type Such a pointer can be converted to type void * and back again with no loss of information

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Generic Pointers A generic pointer cannot be dereferenced with these operators * [ ] subscript On many machines all pointers are the same size However to ensure max portability because of potentially different sizes void * pointer must converted back to pointer of appropriate type before dereferencing

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Dereferencing Generic Pointers void * myGenericPtr; int myValue = 3; myGenericPtr = &myValue; int tempValue = *myGenericPtr; // illegal void * myGenericPtr; int myValue = 3; myGenericPtr = &myValue; int tempValue = *myGenericPtr; // illegal int a = 9; int *intPtr = &a;// point to a cout << *intPtr << endl;// prints 9 void* genPtr = static_cast (&a);// preferred C++ style cast int* intPtr2 = static_cast (genPtr); // preferred C++ style cast cout << *intPtr2 << endl; // prints 9 int a = 9; int *intPtr = &a;// point to a cout << *intPtr << endl;// prints 9 void* genPtr = static_cast (&a);// preferred C++ style cast int* intPtr2 = static_cast (genPtr); // preferred C++ style cast cout << *intPtr2 << endl; // prints 9

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Null Pointers Dereferencing a pointer with No assigned value gives undetermined results A value of 0 is Illegal

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Null Pointers  When declared, local pointers contain whatever values were in memory at time…. ….. dereferencing treats that value as an address  Global and Static Pointers are initialized to 0….. …..dereferencing usually gives runtime error and program termination

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Null Pointers ANSI C++ offers solution and defines a special pointer null pointer Its value points to no object or function (void *) 0 Special macro NULL defined in header file Definition depends upon compiler and operating system Often defined as NULL ((void *) 0 )

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Function Pointers The pointers we’ve discussed so far have been pointers to data We can also define pointers to functions or function pointers syntax return type (* functionPointer) ( ) arg list may be empty syntax return type (* functionPointer) ( ) arg list may be empty

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Function Pointers int (* intFunctPtr) (); Read as intFunctPtr is  A pointer to a function  Taking no args  Returning an int int (* intFunctPtr) (); Read as intFunctPtr is  A pointer to a function  Taking no args  Returning an int double (* doubleFunctPtr) (int, char); Read as doubleFunctPtr is  A pointer to a function  Taking two args: an int and a char  Returning a double double (* doubleFunctPtr) (int, char); Read as doubleFunctPtr is  A pointer to a function  Taking two args: an int and a char  Returning a double

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Function Pointers How do we obtain a pointer to function…. ….There are several ways  Use address of operator, &  Use function name with no parameter list int (* intFunctPtr) (); int myFunction(); intFunctPtr = &myFunction; or intFunctPtr = myFunction; int (* intFunctPtr) (); int myFunction(); intFunctPtr = &myFunction; or intFunctPtr = myFunction;

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Dereferencing Function Pointers We can also dereference a function pointer in several ways (* functPtr)( argument-list) functPtr(argument-list) double (*doubleFunctPtr)(int, char); double yourFunction (int, char) doubleFunctPtr = yourFunction; (*doubleFunctPtr)(3, ‘b’); int (* intFunctPtr) (); int myFunction(); intFunctPtr = myFunction; (*intFunctPtr)();

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Function Pointers Function and Data pointers may have significantly different representations  Based upon machine architecture  Byte Ordering  Alignment requirements  Sizes  Memory models Conversion between function and data pointers in ANSI C++ Has undefined behavior Conversion to or from type void * in ANSI C++ No guarantee of safety

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Indirect Reference In addition to address of a variable a pointer variable can contain the address of another pointer ….We have pointer to pointer To retrieve the value we must apply dereference operator twice syntax type ** pointerName

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Indirect Reference Let’s declare an integer int myInt = 3 A pointer to an int int* myIntPrt = &myInt; …and a pointer to that pointer int** myIntPtrPtr = &myIntPtr; Let myInt be stored at memory address 4000 myIntPtrPtr be stored at address 3000 myIntPtr be stored at address 3020

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Indirect Reference Thus the expression int myValue = ** myIntPtrPtr Assigns the value 3 to the variable myValue Since myIntPtrPtr is pointing to 1. Memory location Which points to memory location Which contains the value 0003 Since myIntPtrPtr is pointing to 1. Memory location Which points to memory location Which contains the value 0003

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Indirect Reference Similarly int myValue = 4; **myIntPtrPtr = myValue; Places the value 4 into memory location 4000

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Reference Types C++ introduces an additional way of referring to an object Called reference A reference serves as an alias or alternate name for an object

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Reference Types Rules for references A reference Must be initialized when created like a const A pointer initialized any time Once initialized to an object it cannot be changed to refer to another object A pointer can be pointed to different object anytime syntax type & varName = aValue

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Reference Types Cannot  Have NULL reference  Point to reference  Have an array of references  Take the address of a reference  Compare references  Assign to them  Do arithmetic on them

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Initialization of Reference Types A non const - only initialized to lvalue of exact type lvalue is value that can appear on left hand side of an assignment statement unsigned char mine; int d1, d2; int &a = 1024;// illegal - not lvalue char &b = mine;// illegal - not exact type int &c = d1 + d2;// illegal - not lvalue

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays Initialization of Reference Types const - can have an rvalue that is an lvalue not of the exact type rvalue can only appear on right hand side of an assignment statement unsigned char mine; int d1, d2; const int = 1024;// legal const char &b = mine;// legal const int &c = d1 + d2;// legal

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays References vs. Pointers Do not support pointer like declarations Cannot have arrays of references Reference to arrays We can’t declare an array of references….. int& v[ ];// array of references to ints ….because v[i]  *(v + i)// pointer to a reference We can’t declare an array of references….. int& v[ ];// array of references to ints ….because v[i]  *(v + i)// pointer to a reference

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays References as Parameters References can be used as parameters in a function call Pass by value... Function never accesses the actual arguments Manipulates local copy stored on the stack Changes made to local copies not always suitable  Large objects passed  args must be modified Pass by value... Function never accesses the actual arguments Manipulates local copy stored on the stack Changes made to local copies not always suitable  Large objects passed  args must be modified Pass by reference…. Function accesses actual arguments Address of args is passed If we don’t want arg to be changed Use const specifier Pass by reference…. Function accesses actual arguments Address of args is passed If we don’t want arg to be changed Use const specifier

Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays References as Parameters void incrementR (int &number); void incrementV (int number); int main(void) { int number = 10; int number1 = 20; incrementR(number); cout << number << endl; // Will print 11 incrementV (number1); cout << number1 << endl; // Will print 20 return 0; } void incrementR (int &number); void incrementV (int number); int main(void) { int number = 10; int number1 = 20; incrementR(number); cout << number << endl; // Will print 11 incrementV (number1); cout << number1 << endl; // Will print 20 return 0; } void incrementR (int &aNumber) { aNumber++; // Passed by reference } void incrementV (int aNumber) { aNumber++; // Passed by value } void incrementR (int &aNumber) { aNumber++; // Passed by reference } void incrementV (int aNumber) { aNumber++; // Passed by value }