Pointers, Dynamic Data, and Reference Types

Similar documents
Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Propedéutico de Programación

Pointers and Dynamic Memory Allocation

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


CS201- Introduction to Programming Current Quizzes

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

Exam 3 Chapters 7 & 9

a data type is Types

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Object Reference and Memory Allocation. Questions:

Dynamic Memory Allocation

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

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

Pointers II. Class 31

Dynamic Allocation in C

Variation of Pointers

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

CA31-1K DIS. Pointers. TA: You Lu

Input And Output of C++

Variables, Memory and Pointers

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

Launchpad Lecture -10

Lecture 2, September 4

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

[0569] p 0318 garbage

Arrays and Pointers. Overview. Arrays Introducing Pointers C-Style Character Strings Multidimensioned Arrays

04-17 Discussion Notes

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

Constants, References

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

377 Student Guide to C++

Tokens, Expressions and Control Structures

Memory and C++ Pointers

C Pointers. 6th April 2017 Giulio Picierro

Common Misunderstandings from Exam 1 Material

Dynamic Allocation of Memory

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

CSC 211 Intermediate Programming. Arrays & Pointers

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Structured Data. CIS 15 : Spring 2007

Pointers and Terminal Control

Homework #3 CS2255 Fall 2012

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

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Understanding Pointers

CS201 Latest Solved MCQs

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Memory and Pointers written by Cathy Saxton

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

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

What is an algorithm?

6.096 Introduction to C++ January (IAP) 2009

CSC1322 Object-Oriented Programming Concepts

CS349/SE382 A1 C Programming Tutorial

CMSC 202 Midterm Exam 1 Fall 2015

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

Pointers, Arrays and C-Strings

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

REFERENCES, POINTERS AND STRUCTS

CS 222: Pointers and Manual Memory Management

Separate Compilation Model

C++ for Java Programmers

Tema 6: Dynamic memory

CS 376b Computer Vision

Pointers. Memory. void foo() { }//return

Lab 3. Pointers Programming Lab (Using C) XU Silei

Dynamic Allocation in C

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

ALL ABOUT POINTERS C/C++ POINTERS

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

Objectives. In this chapter, you will:

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

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++

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

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

Arrays, Pointers and Memory Management

Fast Introduction to Object Oriented Programming and C++

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

Intermediate Programming, Spring 2017*

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Array Elements as Function Parameters

Lectures 5-6: Introduction to C

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

C-types: basic & constructed. C basic types: int, char, float, C constructed types: pointer, array, struct

Section - Computer Science. int main() {! int a=10,b=20;! printf("a:%d B:%d\n",a,b);! a=(a+b)-(b=a);! printf("a:%d B:%d\n",a,b);!

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

Quiz 0 Review Session. October 13th, 2014

Kurt Schmidt. October 30, 2018

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

C++ for Java Programmers

CSE 307: Principles of Programming Languages

Lecture Notes on Memory Management

Transcription:

Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1

C++ Data Types simple structured integral enum floating array struct union class char short int long bool float double long double address pointer reference 2

Pointers in Array 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 because the value of str itself cannot be changed by assignment. It points to the memory location of a char. Str 6000 H e l l o \0 str [0] [1] [2] [3] [4] [5] [6] [7] 3

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. This is the address of the variable int x; float number; char ch; 2000 2002 2006 x number ch 4

Pointers: Obtaining Memory Addresses The address of a non-array variable can be obtained by using the address-of operator & (dereference operator) int x; float number; char ch; 2000 2002 2006 x number ch cout << Address of x is << &x << endl; cout << Address of number is << &number << endl; cout << Address of ch is << &ch << endl; 5

Pointers: What is a Pointer Variable? A pointer variable is a variable whose value is the address of a location in memory. A variable of type T* can hold the address of an object of type T. To declare a pointer variable, you must specify the type of value that the pointer will point to Examples int* ptr; // ptr will hold the address of an int char** q; // pointer to pointer to char, q will hold the address of a pointer, that pointer is holding the address of a char int* ap[15]; //array of 15 pointers to int const char* p1; char const* p2; //pointer to const char char* const p3; //const pointer to char 6

Pointers: Using a Pointer Variable int x; x = 12; 2000 x 12 int* ptr; ptr = &x; 3000 ptr 2000, &x NOTE: Because ptr holds the address of x, we say that ptr points to x 7

Pointers in String Literals char* p = Hello ; char[] q = Hello ; char* r = Hello ; p[4] = O ; // error: assignment to constant q[4] = O ; // ok, q is an array of 5 characters p == r; // false; implementation dependent 8

Pointers: Reference Operator & int x; x = 12; 2000 x 12 int* ptr; ptr = &x; cout << *ptr; 3000 ptr 2000 NOTE: The value pointed to by ptr is denoted by *ptr 9

Pointers: Dereferencing Operator * int x; x = 12; 2000 x 12 5 int* ptr; ptr = &x; *ptr = 5; 3000 2000 ptr // changes the value at the address ptr points to 5 10

Pointers: The NULL Pointer There is a pointer constant called the null pointer denoted by NULL But NULL is not memory address 0. NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer s job to check for this. while (ptr!= NULL) {... // ok to use *ptr here } 11

Pointers: Address Arithmetic char msg[ ] = Hello ; char* ptr; ptr = msg; *ptr = M ; ptr++; *ptr = a ; msg 3000 H e l l o \0 M a 3000 3001 ptr 12

Pointers: More Example char ch; ch = A ; char* q; q = &ch; *q = Z ; 5000 4000 q 4000 A Z ch 6000 4000 p char* p; p = q; // the rhs has value 4000 // now p and q both point to ch 13

References: References to Variables Reference variable = alias for another variable - Contains the address of a variable (like a pointer) - No need to perform any dereferencing (unlike a pointer) - Must be initialized when it is declared - The notation X& means reference to X int x = 5; int &z = x; // z is another name for x int &y ; //Error: reference must be initialized cout << x << endl; -> prints 5 cout << z << endl; -> prints 5 z = 9; // same as x = 9; cout << x << endl; -> prints 9 cout << z << endl; -> prints 9 14

References: Why Reference Variables Primarily used as function parameters Advantages of using references: you don t have to pass the address of a variable you don t have to dereference the variable inside the called function 15

Reference Variables Example #include <iostream.h> // Function prototypes (required in C++) void p_swap(int *, int *); void r_swap(int&, int&); int main (void){ int v = 5, x = 10; cout << v << x << endl; p_swap(&v,&x); cout << v << x << endl; r_swap(v,x); cout << v << x << endl; return 0; } void p_swap(int *a, int *b) { } int temp; temp = *a; (2) *a = *b; (3) *b = temp; void r_swap(int &a, int &b) { int temp; temp = a; (2) a = b; (3) b = temp; } 16

Dynamic Memory Allocation In C and C++, three types of memory are used by programs: Static memory - where global and static variables live Heap memory -dynamically allocated at execution time -"small" amount of "managed" memory accessed using pointers Stack memory - used by automatic variables 17

3 Kinds of Program Data STATIC DATA: Allocated at compiler time DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function 18

Dynamic Memory Allocation Diagram High-end Stack Heap Run-time allocated memory static data Program code Compile-time allocated memory Low-end 19

Dynamic Memory Allocation In C, functions such as malloc() are used to dynamically allocate memory from the Heap. In C++, this is accomplished using the new and delete operators new is used to allocate memory during execution time returns a pointer to the address where the object is to be stored always returns a pointer to the type that follows the new 20

Operator new: Syntax new DataType new DataType [] If memory is available, in an area called the heap (or free store) new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. Otherwise, program terminates with error message. The dynamically allocated object exists until the delete operator destroys it. 21

Operator new: Example char* ptr; ptr = new char; 2000??? 5000 ptr *ptr = B ; cout << *ptr; 5000 B NOTE: Dynamic data has no variable name 22

Operator delete: Syntax delete Pointer delete [ ] Pointer The object or array currently pointed to by pointer is deallocated, and the value of pointer is undefined. The memory is returned to the free store. Good idea to set the pointer to the released memory to NULL Square brackets are used with delete to deallocate a dynamically allocated array. 23

Operator delete: Example char* ptr; ptr = new char; *ptr = B ; cout << *ptr; delete ptr; 2000 5000??? ptr 5000 B NOTE: delete deallocates the memory pointed to by ptr 24

Operator delete: Example char *ptr ; ptr = new char[ 5 ]; ptr 3000 6000 NULL??? strcpy( ptr, Bye ); ptr[ 1 ] = u ; delete ptr; ptr = NULL; 6000 B y e \0 u // deallocates the array pointed to by ptr // ptr itself is not deallocated // the value of ptr becomes undefined 25

Take Home Message Be aware of where a pointer points to, and what is the size of that space. Have the same information in mind when you use reference variables. Always check if a pointer points to NULL before accessing it. 26