12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.

Slides:



Advertisements
Similar presentations
1 Pointers. Variable Memory Snapshot 2 int nrate = 10; The variable is stored at specific memory address A variable is nothing more than a convenient.
Advertisements

Engineering Problem Solving with C Fundamental Concepts Chapter 6 Pointers.
DYNAMIC MEMORY MANAGEMENT. int x; When the source code containing this statement is compiled and linked, an executable file is generated. When the executable.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
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.
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.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Stack and Heap Memory Stack resident variables include:
Pointers Pointer a data type stores a memory address points to whatever the memory location contains A pointer is a variable that can store a memory address.
Pointers OVERVIEW.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
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.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Dynamic memory allocation and Pointers Lecture 4.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Review 1 List Data Structure List operations List Implementation Array Linked List.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 22: Pointers.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
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.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 24: Pointers and Dynamic Allocation.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Chapter 7 Pointers Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
STACKS & QUEUES for CLASS XII ( C++).
Pointers and Dynamic Arrays
Chapter 12 – Data Structures
12 C Data Structures.
Lecture 6 C++ Programming
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Chapter 10: Pointers 1.
An Introduction to Pointers
Popping Items Off a Stack Lesson xx
Pointers, Dynamic Data, and Reference Types
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Programming with Pointers
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Engineering Problem Solving with C++, Etter
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Dynamic allocation (continued)
DYNAMIC MEMORY MANAGEMENT
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Pointers, Dynamic Data, and Reference Types
Pointers.
Presentation transcript:

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction to Pointers

4 Addresses and Pointers 4 Pointers to Array Elements 4 Dynamic Memory Allocation 4 Data Structures and the STL. 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 2

ADDRESSES AND POINTERS address operator pointer assignment pointer arithmetic 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 3

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 4 Addresses and Pointers 4 A pointer is an object that holds the memory address of another object.  If a variable p contains the address of another variable q, then p is said to point to q.  If q is a variable at location 100 in memory, then p would have the value 100 ( q ’s address). –Memory snapshot: qp

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 5 Address Operator 4 The operator & is called the address operator. 4 When the & operator is applied to an object, the result is the address of the object. 4 Example: int x=75; cout << "x is " << x; cout << "\nthe addres of x is " << &x; 75 x[0x7fff8164] OUTPUT: x is 75 the address of x is 0x7fff8164

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 6 Pointer Assignment 4 Pointer types are declared using the pointer operator *, also called the dereferencing operator. 4 Syntax - –type *variable_name, *variable_name; –type* variable_name; 4 When declaring more than one pointer variable, the * operator must precede each identifier.

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 7 Example int *iPtr; double* dPtr;  The variable iPtr is declared to be of type pointer to int.  The variable dPtr is declared to be of type pointer to double. 4 Neither variable in this example has been initialized. iPtrdPtr ??

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 8 Example int *iPtr, i=6; char* s, str[] = "example"; double *dPtr, d=1.25; iPtr s dPtr 6 "example" 1.25 i str d

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 9 Initialization and Assignment 4 Pointer types may be initialized at the time they are declared. 4 Pointer types may be assigned new values using the assignment operator.

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 10 Example – Initial Pointers to NULL int *iPtr=0; char *s=NULL; //predefined constant in iostream double *dPtr=NULL; iPtr s dPtr

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 11 Assignment 4 The assignment operator (=) is defined for pointers of the same base type. 4 The right operand of the assignment operator can be any expression that evaluates to the same type as the left operand. Example: int x, *xp, *ip; xp = &x; ip = xp; x xp ip

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 12 The Base Type 4 The base type of a pointer refers to the type of object the pointer is referencing. 4 The base type of a pointer defines the size of the object the pointer is referencing. 4 The size of a pointer is independent of its base type. –p and q are the same ( 4 bytes**), but p points to 4 bytes** and q points to 8 bytes** ** compiler dependent

Example: 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 13 int p(5), *iPtr=&p; double q, *dPtr=&q; dPtr p q 5 ? ? iPtr  sizeof p is 4  sizeof q is 8  sizeof iPtr is 4  sizeof dPtr is 4

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 14 Base Type 4 A pointers base type determines how the object referenced by the pointer will be interpreted. 4 The declaration: int *p; declares p to be a pointer to int. What ever p points to will be interpreted as an int, ie 4 bytes. 4 Base type also defines pointer arithmetic.

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 15 Pointer Arithmetic 4 Four arithmetic operations are supported: +, -, ++, -- 4 Arithmetic is performed relative to the base type of the pointer. 4 When applied to pointers, ++ means increment pointer to point to next object. Example: p++; –if p is defined as int *p, p will be incremented by 4 (bytes). –if p is defined as double *p, p will be incremented by 8(bytes).

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 16 Example int *p; cout << "size of char is " << sizeof(char) << endl; cout << "size of int is " << sizeof(int) << endl; cout << "size of double is " << sizeof(double) << endl; cout << "size of float is " << sizeof(float) << endl; cout << "the size of p is " << sizeof(p) << endl; Output: size of char is 1 size of int is 4 size of double is 8 size of float is 4 the size of p is 4

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 17 Practice! int q=6; int *iPtr = &q; cout << "iPtr is " << iPtr << endl; cout << "*iPtr is " << *iPtr << endl; cout << "++*iPtr, is " << ++*iPtr << endl; cout << "q is " << q << endl; cout << "iPtr is " << iPtr << endl; cout << "*iPtr++ is " << *iPtr++ << endl; cout << "iPtr is " << iPtr << endl; cout << "q is " << q << endl; Complete the output: iPtr is 0x7fff2f14

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 18 Result of Practice iPtr is 0x7fff2f14 *iPtr is 6 ++*iPtr is 7 q is 7 iPtr is 0x7fff2f14 *iPtr++ is 7 iPtr is 0x7fff2f18 q is 7

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 19 Comparing Pointers 4 You may compare pointers using relational operators 4 Common comparisons are: –check for null pointer (p == NULL) –Note: since NULL evaluates as false, and any other pointer evaluates as true, checking for a null pointer can be done as (!p) –check if two pointers are pointing to the same object (p == q) –Note: (*p == *q) means they are pointing to equivalent, but not necessarily the same data.

POINTERS TO ARRAY ELEMENTS one-dimensional arrays pointers as arguments to functions 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 20

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 21 One Dimensional Arrays 4 The name of an array is the address of the first element (i.e. a pointer to the first element). 4 Arrays and pointers may often be used interchangeably. Example int num[4] = {1,2,3,4}, *p; p = num;//same as p = &num[0]; cout << *p <<endl; ++p; cout << *p; output: 1 2

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 22 Arrays and Pointers 4 You can index a pointer using [] operator. Example: char myString[] = "This is a string"; char *str; str = myString; for(int i =0; str[i]; i++)//look for null cout << str[i]; What does this segment print? This is a string

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 23 Arrays and Pointers 4 When an array is defined, memory is allocated according to the specified size of the array. 4 The name of an array is a pointer to the first element. However, the value of the pointer can not be changed. It will always point to the same memory location. 4 When a pointer is defined, 4 bytes* are allocated to store a memory address. 4 The value assigned to a pointer can be modified (reassigned to point to a different object).

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 24 Practice! What does this print? char myString[ ] = "This is a string"; char *strPtr; strPtr = myString; cout << *myString << endl; cout<<myString << endl; cout << *(myString + 1) << endl; strPtr++; cout << *++strPtr << endl; myString++;//not legal 0xfff4c252 strPtr T This is a string h i 0xfff4c252 myString Thisisastring\0

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 25 Arrays of Pointers 4 You may define arrays of pointers like any other data type in C++ int num=8; //declare an array of 10 pointers to int int *iPtrs[10]; //first element is assigned a value iPtrs[0] = &num; //output the value of num cout << *iPtrs[0];

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 26 Pointers As Arguments to Functions 4 Pointers may be passed either "by value" or "by reference". 4 In either case, the pointer can be used to modify the object to which it is pointing. 4 Only when passed by reference can the pointer argument itself be modified.

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 27 Common Pointer Problems 4 Using uninitialized pointers int *iPtr; *iPtr = 100; iPtr has not been initialized. The value 100 will be assigned to some memory location. Which one determines the error. 4 Failing to reset a pointer after altering it’s value. 4 Incorrect/unintended syntax.

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 28 #include int main() { char *aString = "What happens here?"; int len=0; while(*aString++ != '\0') len++; std::cout << len << ": " << aString; return 0; } Does this compile? If not, why? If it does, what is the output? Explain? Practice! Yes 18:

DYNAMIC MEMORY ALLOCATION new delete dynamically allocated arrays 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 29

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 30 Dynamic Allocation Using new and delete 4 Storage for data is allocated as needed from the free memory area known as the heap. 4 Run-time stack –Local variables –Formal parameters –Managed by the compiler 4 Heap –Dynamic storage –Managed by storage allocator Stack Heap Global data Program code

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 31 Dynamic Memory Allocation 4 Dynamically allocated memory is defined at runtime. 4 Dynamic allocation of memory allows for more efficient use of a finite resource. 4 Dynamic allocation is often used to support dynamic data structures such as stacks, queues, linked lists and binary trees. 4 Dynamically allocated memory should be freed during execution when it is no longer needed.

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 32 Operator new 4 Replaces malloc() used in C 4 Allocates a block of memory from the heap. 4 Returns the address of the first byte.  If allocation fails, new throws and exception that terminates the program (or returns NULL on older compilers).

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 33 Example int *iPtr; iPtr = new int; // 4 bytes are allocated // iPtr points to 1 st byte double *dPtr; dPtr = new double[20]; // 160 bytes allocated // dPtr points to 1 st byte ? ? ? ? ? … ? ? heap iPtr dPtr

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 34 Initializing Dynamically Allocated Memory 4 To initialize a dynamically allocated object, the initial value is provided inside parentheses following the type. 4 Example: int *ptr; ptr = new int(100); //4 bytes allocated //initial value: 100

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 35 int main() { int *iPtr, *jPtr, i; iPtr = new int; jPtr = new int(3); double *dPtr; dPtr = new double[6]; *iPtr = 7; cout << *iPtr << ',' << *jPtr << endl; for(i=0; i<6; i++) dPtr[i] = 5; for(i=0; i<6; i++) cout << (*dPtr)++ << ' '; cout << endl; for(i=0; i<6; i++) cout << dPtr[i] << ' '; return 0; } OUTPUT 7, EXPLAIN Practice:

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 36 Operator delete 4 Replaces free() used in C.  The delete operator frees memory allocated by new.  Using delete to attempt to free any other type of address will result in errors.

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 37 delete Example int *ptr; ptr = new int (100); cout << *ptr;//see if it worked value of ptr is now undefined 100 ptr delete ptr;//free the memory ? ptr

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 38 Example: Dynamically Allocated Arrays double *dptr; const int SIZE = 10; dptr = new double[SIZE];//80 bytes for(int i=0; i<SIZE; ++i) cin >> dptr[i]; fun1(dptr, SIZE); // pass array to fun1 delete [] dptr; //free all 10 elements

12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 39 Example using delete int main() { int *iPtr, *jPtr; iPtr = new int(2); jPtr = new int(3); cout << *iPtr << ',' << *jPtr << endl; delete iPtr; delete jPtr; cout << *iPtr << ',' << *jPtr << endl; int *dPtr; dPtr = new int(5); cout << iPtr << ',' << jPtr << endl; cout << *iPtr << ',' << *jPtr << endl; cout << dPtr << endl; return; } What output would you expect from this code?

DATA STRUCTURES AND THE STL list stack queue 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 40

List 4 A list is a data structure organized as a collection of elements, or nodes, that are linked by pointers. 4 Elements can be added at any position in a list in constant time by reassigning pointers. 4 List have many useful applications in the organization large amounts of data. 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 41

The list class 4 list is a class template defined in the header file list. #include list word; //list of strings 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 42

list Methods o Elements can be added to and removed from any position in a list using the appropriate method and an iterator. o An iterator is similar to a pointer, but is usually implemented as a class object. o Common Methods: bool empty() iterator insert() iterator remove() iterator begin() iterator end() 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 43

Example list wordList; list ::iterator iter = wordList.begin(); iter = wordList.insert(iter,"hello"); wordList.insert(iter,"world"); for(iter=wordList.begin(); iter!= wordList.end(); iter++) cout << *iter << " "; 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 44 output: hello world

Queue 4 A queue is known as a first-in-first-out (FIFO) data structure. 4 Items are added to the end of a queue and removed from the front of the queue. 4 Queues have many useful applications, including processing requests. 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 45

The queue class 4 queue is a class template defined in the header file queue. #include queue printIDs; //queue of ints 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 46

queue Methods bool empty() void pop()//remove from front void push()//add to end data-type front()//return front data-type back()//return end 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 47

Example #include … queue theQueue; theQueue.push(10); theQueue.push(20); cout << theQueue.front(); //output 10 cout << theQueue.back(); //output 20 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 48

Stack 4 A stack is known as a last-in-first-out (LIFO) data structure. 4 Items are added to and removed from the top of the stack. 4 Stacks are essential in the design of compilers and for implementing recursion. 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 49

The stack class 4 stack is a class template defined in the header file stack. #include stack theStack; //stack of ints 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 50

stack Methods bool empty() void pop() //remove from top void push() //add to top data-type top()//return top 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 51

Example #include … stack theStack; theStack.push(10); theStack.push(20); cout << theStack.top(); //output 20 theStack.pop(); cout << theStack.top(); //output 10 12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 52