Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

Similar documents
Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

C++ for Java Programmers

Pointers. Variable Declaration. Chapter 10

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers, Dynamic Data, and Reference Types

DECLARAING AND INITIALIZING POINTERS

BITG 1113: POINTER LECTURE 12

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Language comparison. C has pointers. Java has references. C++ has pointers and references

Homework #3 CS2255 Fall 2012

CS201- Introduction to Programming Current Quizzes

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

4/27/2014. Templates II. Warmup Write the templated Swap function. Class Templates CMSC 202

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

CS2141 Software Development using C/C++ C++ Basics


FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

6.096 Introduction to C++ January (IAP) 2009

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

CS242 COMPUTER PROGRAMMING

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

by Pearson Education, Inc. All Rights Reserved.

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Pointers, Arrays and C-Strings

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Fri, Jan 18, 2013

Pointer Data Type and Pointer Variables

CMSC 202 Midterm Exam 1 Fall 2015

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Introduction to Programming Using Java (98-388)

LECTURE 02 INTRODUCTION TO C++

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

C++ Programming: From Problem Analysis to Program Design, Third Edition

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Dynamic Allocation of Memory

Introduction to Linked Lists

Lecture on pointers, references, and arrays and vectors

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Programming, numerics and optimization

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Mon, Jan 20, 2014

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Functions, Arrays & Structs

Chapter 1: Object-Oriented Programming Using C++

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

a data type is Types

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

CS2255 HOMEWORK #1 Fall 2012

Arrays, Pointers and Memory Management

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Linked List using a Sentinel

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

C++ Programming Chapter 7 Pointers

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 6: Pointers

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Introduction to Programming EC-105. Lecture 2

[0569] p 0318 garbage

Assist. Prof. Dr. Caner ÖZCAN

Objectives. In this chapter, you will:

CPSC 427a: Object-Oriented Programming

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

Module Operator Overloading and Type Conversion. Table of Contents

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CPSC 427: Object-Oriented Programming

CS250 Final Review Questions

Fundamentals of Programming CS-110. Lecture 2

Chapter 2 Basic Elements of C++

CSC1322 Object-Oriented Programming Concepts

In Java we have the keyword null, which is the value of an uninitialized reference type

Short Notes of CS201

Object Reference and Memory Allocation. Questions:

Operator Overloading in C++ Systems Programming

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

Week 3: Pointers (Part 2)

Kapi ap l S e S hgal P T C p t u er. r S. c S ienc n e A n A k n leshw h ar ar Guj u arat C C h - 8

Chapter 18 - C++ Operator Overloading

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Linked lists Tutorial 5b

CS201 - Introduction to Programming Glossary By

What is an algorithm?

School of Information Technology and Computer Science CSCI192 - Spring Session Revision

Transcription:

Scott Gibson Pointers & Dynamic Memory Lecture #1 Office: LAH 103 Email: sgibson@brookdalecc.edu sgib@optonline.net Web: www.brookdalecc.edu/fac/cos/sgibson Phone: (732) 224 2285 1 2 Pre & Co Requisites Pre Requisites COMP 126: Computer Logic and Design Number systems Basic Hardware Basic Program Design COMP 132: Structured Programming in C++ Co Requisite COMP 233: Object Oriented Programming Using C++ 3 Random Access Memory 1 Byte = 8 bits (Binary digits) 2 8 = 256 possible values Location in memory Known as the byte s address Obtainable via the & operator 4 Data Types Atomic Type Sizes Data Representation Number of bytes required Bit pattern Operations supported int short long float double char 32 bits 16 bits 32 bits 32 bits 64 bits 8 bits 5 6 Copyright (c) 2011 Scott L. Gibson 1

Identifiers Operators User defined Must follow C/C++ naming convention Associated with Data type Memory location & returns a memory address First byte of variable sizeof returns a number of bytes Size of data object Size of data type 7 8 Example 1 1 int x = 10; cout << Contents: << x << endl; cout << Size: << sizeof (x) << endl; cout << Location: << &x << endl; system ( pause ); 9 Pointer Variables A variable that holds memory address Definition x Must specify base type Asterisk (*) indicates pointer variable ptr Examples 0x0012FF60??? int* iptr; float *fptr; Must be de referenced to access data 10 10 Address of x: 0x0012FF60 (32256d) Dereferencing Pointers Uses of the * Operator The pointer contains the data object s address Follow the pointer to the data object Use the asterisk (*) before the pointer John Smith 123 Main Street Anytown, NJ 12345 Multiplication distance = speed * time Pointer definition int* ptr; De referencing pointers *ptr = 100; 11 12 Copyright (c) 2011 Scott L. Gibson 2

Initializations Assignment at declaration Address of existing data object Example int data = 15; int* ptr = &data; Always initialize to something NULL Example 1 2 int x = 10; int* ptr = &x; cout << The contents of x: << x << endl; cout << The address of x: << &x << endl; cout << The contents of ptr: << ptr << endl; cout << The address of ptr: << &ptr << endl; cout << The target of ptr: << *ptr << endl; 13 14 Review 1. What does the & operator do? Returns the address of the first byte of the operand 2. How many possible values can an 8 bit hold? 256 3. How is a pointer variable declared? BaseType* ptr; 4. How is a pointer variable de referenced? cout << *ptr; Pointers to Constants Pointers can reference constant data objects Definition const keyword placed before data type const int* cptr; Can point to non constant data objects Cannot change value through constant pointer 15 16 Constant Pointers Contents of pointer variable cannot change Must be initialized at declaration const keyword placed after * int value = 5; int* const ptrc = &value; Can change value through constant pointer Pointer contents cannot change Arrays and Pointers Array name is a constant pointer Arrays can be used like pointers Pointers can be used like arrays Dereferencing pointer = indexing i array Example short numbers [5]; numbers [0] numbers [1] numbers [2] numbers [3] numbers [4] numbers 17 18 Copyright (c) 2011 Scott L. Gibson 3

Pointer Arithmetic Manipulate pointers via math operations Add multiples of the base type s size Example iptr Pointer to integer (integers are 4 bytes) Currently contains 0x7e00 iptr + 1 Evaluates to 0x7e04 Other Pointer Operators Logical operators ==,!=, <, <=, >, >= Simple comparisons betweenbinaryvalues binary Unary & binary addition & subtraction +, ++, +=, = 19 20 Example 1 3 short list [] = 1, 2, 3, 4, 5; for (int i = 0; i < 5; ++i) cout << (list + i) << endl; for (short* p = list; p < &(list [5]); ++p) cout << *ptr << endl; system ("pause"); Pointer Parameters Pass by pointer Similar to pass by reference Implemented with pass by value Arguments become mutable Caller must pass address Function receives pointer to data object Example void DoubleValue (int* n) *n *= 2; 21 22 Allocated at runtime Single data objects Arrays Variable sizes Operators new delete Dynamic Memory Operator: new Allocates dynamic memory Atomic types (i.e., int, float, etc.) Arrays Class Syntax ptr = new datatype; For array, add [dimension] after datatype For class, add (params) after datatype 23 24 Copyright (c) 2011 Scott L. Gibson 4

Operator: delete Review Deallocates dynamic memory Use onlywith new Syntax delete objptr; for arrays, use [] (empty) after delete 5. If an int pointer containing the value 0x5000 has 1 is added to it, what value will it contain? 0x5004 6. Write a statement that dynamically allocates an array of 25 integers. int* array = new int [25]; 25 26 Review Class Member Selection 7. Write a statement that dynamically allocates an instance of class cgameentity using the default constructor. cgameentity* ptr = new cgameentity; 8. De allocate the two pointers above. delete [] array; delete ptr; Using statically declared object Dot member specifier Object.Method (); Using dynamically declared object Arrow member specifier ObjectPtr >Method (); 27 28 #include <iostream> using namespace std; Example 1 4 class cpoint private: int m_x, m_y; public: cpoint () m_x = m_y = 0; cpoint (int x, int y) Set (x, y); cpoint (const cpoint& pt) Set (pt.m_x, pt.m_y); void Set (int x, int y) m_x = x; m_y = y; int GetX () return m_x; int gety () return m_y; void Print (ostream* out) *out << '(' << m_x << ", " << m_y << ')'; ; 29 30 Copyright (c) 2011 Scott L. Gibson 5

int x = rand () % 10; int y = rand () % 10; cpoint* pt = new cpoint (x, y); pt->print (&cout); cout << endl; int size = rand () % 50; cpoint* ptlist = new cpoint [size]; for (int i = 0; i < size; ++i) x = rand () % 10; y = rand () % 10; ptlist [i].set (x, y); int count = 0; for (int i = 0 ; i < size; ++i) ptlist [i].print (&cout); ++count; 31 32 if (count >= 13) cout << endl; count = 0; cout << endl; delete pt; delete [] ptlist; system ("pause"); Data Structures Represent data efficiently Time efficiency: minimizing run time Memory efficiency: minimizing memory usage Demonstrate relationships between data elements Enforce a processing order Model real world problems 33 34 Arrays vs. Linked Lists Fundamental Design Arrays Contiguous storage Random access Fixed size Linked Lists Non contiguous storage Sequential access Expand and contract as needed Series of dynamically allocated nodes Data Link to the next node Single pointer to the first node TopPtr EndPtr (Optional) Data 1 Data 2 Data 3 NULL 35 36 Copyright (c) 2011 Scott L. Gibson 6

Linked List Implementation #include <iostream> using namespace std; class cnode private: int m_data; cnode* m_next; public: cnode (int data) m_data = data; m_next = NULL; void SetData (int data) m_data = data; int GetData () return m_data; void SetNext (cnode* next) m_next = next; cnode* GetNext () return m_next; ; 37 38 class clist private: cnode* m_top; cnode* m_end; int m_size; public: clist () m_size = 0; m_top = m_end = NULL; clist (int data) m_size = 1; m_top = m_end = new cnode (data); ~clist () while (m_size > 0) RemoveFront (); 39 40 void AddFront (int data) cnode* temp = new cnode (data); if (m_size == 0) m_top = m_end = temp; temp->setnext (m_top); m_top = temp; void AddEnd (int data) cnode* temp = new cnode (data); if (m_size == 0) m_top = m_end = temp; m_end->setnext (temp); m_end = temp; ++m_size; ++m_size; 41 42 Copyright (c) 2011 Scott L. Gibson 7

int RemoveFront () if (m_size > 0) int data = m_top->getdata (); if (m_size == 1) delete m_top; m_top = m_end = NULL; cnode* top = m_top; m_top = m_top->getnext (); delete top; --m_size; return data; 43 44 int RemoveEnd () if (m_size > 0) int data = m_end->getdata (); if (m_size == 1) delete m_end; m_top = m_end = NULL; cnode* cur = m_top; while (cur->getnext ()!= m_end) cur = cur->getnext (); delete m_end; m_end = cur; --m_size; return data; 45 46 void PrintAll (ostream& out) cnode* cur = m_top; while (cur!= NULL) out << cur->getdata () << " "; cur = cur->getnext (); out << endl; ; int GetSize () return m_size; bool IsEmpty () return (m_size!= 0); 47 48 Copyright (c) 2011 Scott L. Gibson 8

clist list; for (int i = 0; i < 10; ++i) list.addfront (i*10); list.addend (i*5); list.printall (cout); system ("pause"); Vector Like arrays Homogeneous sequence of data Random access to contents Unlike arrays Might not have a predefined size Able to "grow" as needed 49 50 Vector Implementation Encapsulated in class Pointer to dynamic array size of array Methods Resize array Get array size Assign array element Retrieve array element Summary Memory Bits & bytes Address of operator & Pointers Defining, assigning, and de referencing Star operator * Dynamic Memory Allocating & de allocating 51 52 Assignment #1 Due next week Jan 31 2011 Implement a simple vector class Use a dynamically allocated array Allow assignments and retrievals allow resizing while in use 53 Copyright (c) 2011 Scott L. Gibson 9