Writing a Good Program 6. Pointers and Arrays

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
 2006 Pearson Education, Inc. All rights reserved Pointers.
1 Writing a Good Program 5. Objects and Classes in C++
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
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.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
February 11, 2005 More Pointers Dynamic Memory Allocation.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers OVERVIEW.
1 Writing a Good Program 8. Elementary Data Structure.
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.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Dynamic Allocation Joe Meehean. Dynamic Allocation Memory for local objects is automatically created and reclaimed memory is created for it at beginning.
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.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Chapter 7 Pointers: Java does not have pointers. Used for dynamic memory allocation.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT9: Pointer I CS2311 Computer Programming.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
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.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
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.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
Pointers and Memory Overview
Pointers Revisited What is variable address, name, value?
8 Pointers.
Dynamic Memory Allocation
Popping Items Off a Stack Lesson xx
Dynamic Memory A whole heap of fun….
Presentation transcript:

Writing a Good Program 6. Pointers and Arrays

6.1 Pointers Computer Programming and Basic Software Engineering 6. Pointers and Arrays 6.1 Pointers

How memory is used in C++? Computer Programming and Basic Software Engineering 6. Pointers and Arrays How memory is used in C++? The whole big piece of memory is divided into 4 areas: Code Space - for the storage of program code Stack - for the storage of local variables, passed parameters. Global Name Space - for the storage of global variables Free store - for the storage of dynamically created data

How memory is used in C++? Computer Programming and Basic Software Engineering How memory is used in C++? 6. Pointers and Arrays funcB() { Cat Frisky; return; } funcA() { int a; main() { Statements; funcA(); Statements; funcB(); Free Store or the heap Global Name Space Code Space The Stack

What is the Address of a Variable? Computer Programming and Basic Software Engineering 6. Pointers and Arrays What is the Address of a Variable? A variable is a storage space in memory. Every variable has a memory address. Each byte has an address Each variable has the starting-byte address Variables char a int b short int c bool d Memory 30 0A 21 3A 51 44 20 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 The character '0' a = 30 Address of a = 0100 b = 0A 21 3A 51 Address of b = 0101 c = 44 20 Address of c = 0105 All values written in hexadecimal but binary in reality

The addresses of shortVar, longVar and sVar Computer Programming and Basic Software Engineering What is the Address of a Variable? 6. Pointers and Arrays In C++, the symbol & is used to indicate the address of a variable. #include <iostream> using namespace std; int main() { unsigned short shortVar = 5; unsigned long longVar = 65535; long sVar = -65535; cout << "shortVar:\t" << shortVar; cout << "\tAddress of shortVar:\t"; cout << &shortVar << "\n"; cout << "longVar:\t" << longVar; cout << "\tAddress of longVar:\t"; cout << &longVar << "\n"; cout << "sVar:\t\t" << sVar; cout << "\tAddress of sVar:\t"; cout << &sVar << "\n"; return 0; } The addresses of shortVar, longVar and sVar

What is the Address of a Variable? Computer Programming and Basic Software Engineering 6. Pointers and Arrays What is the Address of a Variable? Variable and address of a variable are different.

Computer Programming and Basic Software Engineering 6. Pointers and Arrays What is a Pointer? In many situations, we want to store the address of a variable into a particular memory location. Variables char a int b (address of a) pa Memory 10 0A 21 3A 51 00 00 01 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 pa is the pointer of a pa is a variable that can store the address of a. In C++, every address has 4 bytes. So we need to reserve 4 bytes of memory to store the address of a .

Computer Programming and Basic Software Engineering What is a Pointer? 6. Pointers and Arrays In C++, every variable needs to have its type declared. int abc; // means abc belongs to the type of integer. CAT Felix; // means Felix belongs to the class CAT If we want to declare the type of pa, which stores the address of a variable a, how should we do it?  How about address pa; Not good enough, since it does not tell the nature of a  How about (address of a character) pa; Better, but look too clumsy

Computer Programming and Basic Software Engineering What is a Pointer? 6. Pointers and Arrays C++ uses an elegant way to solve the problem (but need some time to understand!). It introduces a symbol *.  means the content of an address. pa's content is an address, the memory content of that address is a character Variables char a int b char *pa Memory 10 0A 21 3A 51 00 00 01 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 char *pa indicates that the memory content of the address. stored in pa is a character. pa is indirectly declared to be an address of character.

We modify a indirectly by using its address Computer Programming and Basic Software Engineering What is a Pointer? 6. Pointers and Arrays We can modify the content of a memory location using pointer. Variables char a int b char *pa Memory 30 0A 21 3A 51 00 00 01 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 char *pa, a=0x30; // 48 cout << a; // a = '0' pa = &a; // pa = 0100 cout << *pa; // *pa = 30 *pa = 49; // a = '1' cout << a; We modify a indirectly by using its address

Computer Programming and Basic Software Engineering 6. Pointers and Arrays #include <iostream> using namespace std; typedef unsigned short int USHORT; int main() { USHORT myAge; // a variable USHORT * pAge = 0;// a null pointer, pAge=0, not *pAge=0 // Don’t let it become wild pointer (point to unknown) myAge = 5; cout << "myAge: " << myAge << "\n"; pAge = &myAge; // assign address of myAge to pAge cout << "*pAge: " << *pAge << "\n\n"; cout << "*pAge = 7\n"; *pAge = 7; // *pAge=7, not pAge=7, sets myAge to 7 cout << "*pAge: " << *pAge << "\n"; cout << "myAge: " << myAge << "\n\n"; cout << "myAge = 9\n"; myAge = 9; return 0; }

Computer Programming and Basic Software Engineering 6. Pointers and Arrays

Why Pointer? - Using Free Store Computer Programming and Basic Software Engineering Why Pointer? - Using Free Store 6. Pointers and Arrays Pointer allows us to handle the memory in Free Store. The memory Free Store is opened to all functions. Pointer helps us to identify the part of memory in Free Store that is being used by a particular function or object. To use the memory in Free Store: 1. Make a claim to the system how much memory is required. 2. System allocates a memory space with big enough size. 3. System returns a pointer value which is the starting address of that memory space. 4. When the memory space is not required, release it back to the system for other functions.

Computer Programming and Basic Software Engineering new and delete 6. Pointers and Arrays The keywords new and delete help us claim and release memory in Free Store. Claim a piece of memory in Free Store with size that is equal to an unsigned short integer. unsigned short int * pPointer; pPointer = new unsigned short int; : // after using the memory space delete pPointer; // return it to system We claim memory with size equals to 2 integers. pPointer2 now points to the starting address of this memory space. int * pPointer2; pPointer2 = new int[2]; : // after using the memory space delete [] pPointer2; // return it to system Results unpredictable is no []

pPointer = 8004 Free Store Memory Address Computer Programming and Basic Software Engineering 6. Pointers and Arrays int * pPointer; unsigned short int * pPointer2; pPointer = new int; : pPointer2 = new unsigned short int [2]; delete pPointer; // return it to system delete [] pPointer2; // return it to system pPointer = 8004 pPointer2 = 8008 Free Store Memory Address 8003 8004 8005 8006 8007 8008 8009 800A 800B 800C

Computer Programming and Basic Software Engineering Exercise 6.1 6. Pointers and Arrays The program on the next page will introduce the problem of memory leaks (the system cannot get back the memory allocated to the program) and execution error. Build the program and step over each line of code using the Run- time Debugger. Answer the following questions: What is the address of localVariable? What is the value of pHeap after executing line 6? What is the value of pHeap after executing line 11? Assume that you can finish executing the program. Do you think you can free the memory claimed by the new statement in line 6? If no, why not? Modify the program such that we can free the memories claimed by both new statements in line 6 and line 11.

Computer Programming and Basic Software Engineering 6. Pointers and Arrays #include <iostream> using namespace std; int main() { int localVariable = 5; int * pLocal = &localVariable; int * pHeap = new int; //line 6 *pHeap = 7; cout << "localVariable: " << localVariable << "\n"; cout << "*pLocal: " << *pLocal << "\n"; cout << "*pHeap: " << *pHeap << "\n"; pHeap = new int; //line 11 *pHeap = 9; delete pHeap; return 0; }

delete a pointer ≠ remove a pointer, it still exists Computer Programming and Basic Software Engineering Stray (Wild or Dangling) Pointers 6. Pointers and Arrays When one deletes a pointer, the associated memory will be given back to system. If one tries to use that pointer again without reassigning it, the result is unpredictable. To ensure one will not use the deleted pointer again, always assign the pointer with the value 0 after delete. A stray (or wild, dangling) pointer is the pointer that has been deleted but without assigning to null. delete a pointer ≠ remove a pointer, it still exists NULL points to ROM int *pNum = new int(5); // Initialize *pNum to 5 delete pNum; pNum = 0; // To ensure the program will crash rather // than unpredictable if one reuses it

Creating Objects in the Free Store Computer Programming and Basic Software Engineering Creating Objects in the Free Store 6. Pointers and Arrays Similar to integer, we can create objects in the Free Store. Free Store or the heap Size enough for a Cat Cat *pCat = new Cat; pCat pCat stores the beginning address of the memory allocated. When the object is created, its constructor is called. The Stack Object identified by a pointer. Code Space Global Name Space

Deleting Objects Objects in the Free Store can also be deleted. Computer Programming and Basic Software Engineering 6. Pointers and Arrays Deleting Objects Objects in the Free Store can also be deleted. Cat *pCat = new Cat; delete pCat; pCat becomes an identifier of the object created. When an object is deleted, its destructor will be called. Hence the destructor of Cat will be called when the keyword delete is used in the above. (The destructor will also be called if the function that creates the object finishes.)

Example The class SimpleCat Constructor Destructor Computer Programming and Basic Software Engineering 6. Pointers References and Arrays #include <iostream> using namespace std; class SimpleCat { public: SimpleCat(); ~SimpleCat(); int GetAge() const {return itsAge;} void SetAge(int age) {itsAge = age;} private: int itsAge; }; SimpleCat::SimpleCat() { cout << "Constructor called.\n"; itsAge = 1; } SimpleCat::~SimpleCat() { cout << "Destructor called.\n"; Example The class SimpleCat Constructor Destructor

Computer Programming and Basic Software Engineering 6. Pointers and Arrays int main() { cout << "SimpleCat Frisky...\n"; SimpleCat Frisky; cout << "SimpleCat *pRags = new SimpleCat...\n"; SimpleCat * pRags = new SimpleCat; cout << "delete pRags...\n"; delete pRags; cout << "Exiting, watch Frisky go...\n"; return 0; } pRags in the stack, *pRags in the heap Output of the program

Accessing Members of Objects Computer Programming and Basic Software Engineering 6. Pointers and Arrays Accessing Members of Objects To access members of an object, the symbol (.) is used. The Same SimpleCat *pCat = new SimpleCat; (*pCat).SetAge(2); The object pointed by pCat The member function of the object Input parameter of the member function In C++, a shorthand is provided for such member access SimpleCat *pCat = new SimpleCat; pCat->SetAge(2); // The same as before

Computer Programming and Basic Software Engineering 6. Pointers and Arrays #include <iostream> using namespace std; class Object { public: Object(); ~Object(); int GetCnt() const {return *count;} private: int *count; }; Object::Object() { count = new int(1); } // initialize *count to 1 Object::~Object() { delete count;} int main() { Object Obj; return 0; } Question If I declare an object in the stack that has member variables in the heap, what is in the stack and what is in the heap?

Computer Programming and Basic Software Engineering 6. Pointers and Arrays Answer Free Store or the heap 4 bytes on the stack to hold Obj which contains a pointer count. 4 bytes on the heap that is pointed by count of Obj. 4 bytes: *count Obj The Stack 4 bytes: count Code Space Global Name Space

Computer Programming and Basic Software Engineering 6. Pointers and Arrays Pointers Arithmetic Pointers can be added or subtracted from one another if they are of the same type. Variables short int *a, *b Memory 10 0A 21 3A 51 44 20 Address 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 cout << "a = " << a << endl; // Assume a = 0000 b = a + 1; cout << "b = " << b << endl; // b = 0002 cout << "b - a = " << b-a << endl; // b - a = 1

Pointers Arithmetic The same applies to objects. Memory Address Computer Programming and Basic Software Engineering Pointers Arithmetic 6. Pointers and Arrays You should not DIRECTLY assign a value to a pointer, e.g. int *p=0x00110110; The same applies to objects. Variables Cat *a = new Cat; //Assume Cat takes 6 bytes Memory Address 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 Cat *a = new Cat; Cat *b; cout << "a = " << a << endl; // Assume a = 0000 b = a + 1; cout << "b = " << b << endl; // b = 0006 cout << "b - a = " << b-a << endl; // b - a = 1

Computer Programming and Basic Software Engineering Exercise 6.1b 6. Pointers and Arrays Find out the errors in the following programs. Note the error messages when you build these program. Fix the errors and rebuild it to verify your corrections. #include <iostream> using namespace std; int main() { int *pInt; *pInt = 9; cout << "The value at pInt: " << *pInt << endl; return 0; } #include <iostream> using namespace std; int main() { int SomeVariable = 5; cout << "SomeVariable: " << SomeVariable << "\n"; int *pVar = & SomeVariable; pVar = 9; cout << "SomeVariable: " << *pVar << "\n"; return 0; }

Exercise 6.1c Computer Programming and Basic Software Engineering 6. Pointers and Arrays Modify the program you wrote in exercises 5.2 a and b such that a. The program will ask the user if he wants to create the object Felix. If yes, the object is created in the heap. If no, just quit. b. As before, initialize the age and weight of Felix to 5 and 10 using the constructor. Display the age and weight of Felix. c. Ask the user to enter the age and weight of Felix and display them again. d. After printing the age and weight of Felix, the program will repeatedly ask the user whether he wants to (i) enter the age and weight again; (ii) destroy Felix and create again; or (iii) quit the program. Your program should be able to perform the task the user selected. e. Whenever Felix is destroyed, print the current age and weight of Felix using the destructor. f. Comment your program appropriately.

Acknowledgments The slides are based on the set developed by Dr. Frank Leung (EIE).