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.

Slides:



Advertisements
Similar presentations
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
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.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
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;
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
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.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
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.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
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.
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Pointers CSE 5100 Data Structures and Algorithms.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers Pointers are a unique class of variables whose purpose is to “point” to other variables Pointers allow programmers direct access to memory addresses.
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.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Dynamic memory allocation and Pointers Lecture 4.
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.
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:
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
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.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1 Object-Oriented Programming Using C++ A tutorial for pointers.
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.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
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.
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 A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Pointers What is the data type of pointer variables?
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers and Dynamic Arrays
Pointers and Memory Overview
Pointers and Pointer-Based Strings
CNG 140 C Programming (Lecture set 10)
Chapter 10: Pointers 1.
Pointers, Dynamic Data, and Reference Types
Objectives You should be able to describe: Addresses and Pointers
Pointers and Pointer-Based Strings
Presentation transcript:

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 variable Address of variable  Study Programs 9-1 and 9-2  9.1 also uses sizeof function to display number of bytes of storage used #include #include using namespace std; int main() { int num; int num; num = 22; num = 22; cout << "num = " << num << endl; cout << "num = " << num << endl; cout << "The address of ” << “ num = " cout << "The address of ” << “ num = " << &num << endl; return 0; }

Pointers are Variables that Store Addresses of Other Variables Pointers must be declared: Pointers must be declared: Use an indirection operator *Use an indirection operator * Specify the data type that is pointed toSpecify the data type that is pointed to Examples: Examples: int *numAddr;int *numAddr; float *tabPoint;float *tabPoint; char *charPoint;char *charPoint; OS must know OS must know how many bytes to set aside for the variable pointed to The variable pointed to by numAddr is an integer The variable pointed to by tabPoint is a float The variable pointed to by charPoint is a character

Which to Use? References or Pointers? A reference is a pointer with restricted capabilities A reference is a pointer with restricted capabilities Advantage – hides a lot of internal pointer manipulations from programmerAdvantage – hides a lot of internal pointer manipulations from programmer However, pointers can be added, incremented, and are used by many advanced programmers Reference NotationPointer Notation int b; int b;int b; int &a = b; int &a = b; int *a = &b; a = 10; a = 10; *a = 10; (See pnt.cc) a is a reference variable that stores b’s address. a is not a pointer and can store other values

#include // Program 9-3 Page 412 using namespace std: int main() { int *numAddr; // declare a pointer to an int int miles, dist; // declare two integer variables dist = 158; // store the number 158 into dist miles = 22; // store the number 22 into miles numAddr = &miles; // store the 'address of miles' in numAddr cout << "\nThe address stored in numAddr is " << numAddr << endl; cout << "The value pointed to by numAddr is " << *numAddr << endl; numAddr = &dist; // now store the address of dist in numAddr cout << "\nThe address now stored in numAddr is " << numAddr << endl; cout << "The value now pointed to by numAddr is " << *numAddr << endl; return 0; }

Slide 6 of 36

Saving an address Addresses may only be stored in variables of type pointer Addresses may only be stored in variables of type pointer All pointer variables take the same amount of memory, 4 bytes in our system All pointer variables take the same amount of memory, 4 bytes in our system Pointer variables have types: pointer to int, pointer to char, etc. Pointer variables have types: pointer to int, pointer to char, etc. Array names are (constant) pointers that contain the address of the FIRST array element, Array[0] Array names are (constant) pointers that contain the address of the FIRST array element, Array[0]

Indirection Operator *ptr a two-step lookup, i. e. the variable whose address is stored in ptr *ptr a two-step lookup, i. e. the variable whose address is stored in ptr A double lookup A double lookup get the value of ptrget the value of ptr use that value to look up value located in memoryuse that value to look up value located in memory int normal = 99; int *weirdPtr = &normal; cout << normal << ‘ ‘ << *weirdPtr; Output 99 wierdPtr cef4 normal 99 cef4

More on Declaring Pointers int *num1, num2; // pointer to an int and an int int *num1, num2; // pointer to an int and an int int * num1, * num2; // two pointers to int int * num1, * num2; // two pointers to int float* fptr;// pointer to float float* fptr;// pointer to float char * cptr; // pointer to char char * cptr; // pointer to char Type of thing pointed to is used for cin, cout, arithmetic, and comparisons: cout << *fptr; Type of thing pointed to is used for cin, cout, arithmetic, and comparisons: cout << *fptr; When used in an expression *fptr is a float, *cptr is a character, and *num1 is an integer

// Pointer version of findMax #include using namespace std; main () { // cin makes more sense here int n1 = 10, n2 = 5, n3 = 21, n4 = 17, n5 = 33; int* big = &n1; // remember address of n1; n1 is the //biggest so far if (n2 > *big) // Is 5 > 10? big = &n2; // no change if (n3 > *big) // Is 21 > 10? big = &n3; // big <- address of n3 if (n4 > *big) // Is 17 > 21? big = &n4; // no change if (n5 > *big) // Is 33 > 21? big = &n5; // big <- address of n5 cout << *big << " is biggest.\n"; *big = *big * 10; // pointer notation in an expression cout << *big << " is biggest multiplied by 10.\n";}

Array Names as Pointers Every array is implemented with a pointer to the actual data area Every array is implemented with a pointer to the actual data area The pointer is “anonymous” or hiddenThe pointer is “anonymous” or hidden Array name is a constant pointerArray name is a constant pointer Individual element access Individual element access Calculate offset for this element (how many bytes?)Calculate offset for this element (how many bytes?) Add to address of first elementAdd to address of first element Treat like any other pointer, except constant Treat like any other pointer, except constant Pointer to an array element can be treated like an array: ptr[index] or use pointer arithmetic Pointer to an array element can be treated like an array: ptr[index] or use pointer arithmetic

Two ways to Reference Array Elements Array Element Subscript Notation Pointer Notation Element 0 grade[0] *gradePtr *gradePtr Element 1 grade[1] *(gradePtr +1) Element 2 grade[2] *(gradePtr +2) Element 3 grade[3] *(gradePtr +3) Element 4 grade[4] *(gradePtr +4)

Program 9-5, a pointer version of 9-4 See pages // Program pointer access to an array #include using namespace std; int main() { int *gPtr; // declare a pointer to an int int *gPtr; // declare a pointer to an int const int SIZE = 5; const int SIZE = 5; int i, grade[SIZE] = {98, 87, 92, 79, 85}; int i, grade[SIZE] = {98, 87, 92, 79, 85}; gPtr = &grade[0]; // store 1 st element address gPtr = &grade[0]; // store 1 st element address for (i = 0; i < SIZE; i++) for (i = 0; i < SIZE; i++) cout << "Element " << i << " is " cout << "Element " << i << " is " << *(gPtr + i) << endl; return 0; return 0;}

Program // Since array name is CONSTANT pointer, // just use array name with pointer notation // Since array name is CONSTANT pointer, // just use array name with pointer notation #include using namespace std; int main() { const int SIZE = 5; const int SIZE = 5; int i, grade[SIZE] = {98, 87, 92, 79, 85}; int i, grade[SIZE] = {98, 87, 92, 79, 85}; for (i = 0; i < SIZE; i++) for (i = 0; i < SIZE; i++) cout << "Element " << i << " is " cout << "Element " << i << " is " << *(grade + i) << endl; << *(grade + i) << endl; return 0; return 0;}

Slide 21 of 36

Pointers: What’s the Point? Used extensively with strings Used extensively with strings Used for call-by-reference Used for call-by-reference Early form of generic variables Early form of generic variables Since pointers are all the same size, a pointer variable is capable of pointing to any data typeSince pointers are all the same size, a pointer variable is capable of pointing to any data type Allows the programmer to keep track of dynamically allocated memory Allows the programmer to keep track of dynamically allocated memory Used extensively in Data Structures courseUsed extensively in Data Structures course

Memory Management Most of the variables we have used have been automatic, i. e., they are allocated memory when the function begins and destroyed when it ends (Includes globals) Most of the variables we have used have been automatic, i. e., they are allocated memory when the function begins and destroyed when it ends (Includes globals) This allocation uses the program stack – a temporary locationThis allocation uses the program stack – a temporary location Static variables remain allocated and retain value. They are placed in the (permanent) heap. Static variables remain allocated and retain value. They are placed in the (permanent) heap. Dynamically allocated memory comes from the heap Dynamically allocated memory comes from the heap new obtains a block of storagenew obtains a block of storage delete returns it for later usedelete returns it for later use Program 9-7 is an example of new and delete. Linked lists, Section 3 - Chapter 11, is better example Program 9-7 is an example of new and delete. Linked lists, Section 3 - Chapter 11, is better example

Slide 25 of 36

Slide 30 of 36 34

Slide 28 of 36

Increments are Scaled when used with Pointers If ptr is a pointer to an integer… If ptr is a pointer to an integer… ptr++ causes the pointer to point to the next integerptr++ causes the pointer to point to the next integer ptr-- causes the pointer to point to the previous integerptr-- causes the pointer to point to the previous integer ptr++ or ptr-- actually moves four bytesptr++ or ptr-- actually moves four bytes If ptr is a pointer to a double… If ptr is a pointer to a double… ptr++ causes the pointer to point to the next doubleptr++ causes the pointer to point to the next double ptr-- causes the pointer to point to the previous doubleptr-- causes the pointer to point to the previous double ptr++ or ptr-- actually moves eight bytesptr++ or ptr-- actually moves eight bytes If ptr is a pointer to a character… If ptr is a pointer to a character… ptr++ or ptr-- moves ONE byteptr++ or ptr-- moves ONE byte

Slide 31 of 36

KNOW THIS! Pointers behave differently with numbers than with character arrays /* Pointers to numbers vs. */ /* Pointers to character strings */ /* What is accessed or displayed? */ /* */ /* Pointer to With * Without * */ /* */ /* int/float int/float address */ /* */ /* char char BYTE string from there*/ Look at numsVSchars.cc

Common Errors int location = &num; // location is not a pointer variable, no* (Use descriptive variable names: numAddr, fPtr, chPtr, ptr…) Int * ptr1, ptr2;// without *, ptr2 is not a pointer int nums[3], *ptr; Use ptr = nums; or ptr = &nums[0]; NOT ptr = &nums; // nums is already a const pointer int *ptr = &99;// can’t take address of literal Int *ptr = &(diameter * PI); // nor of an expression