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.

Slides:



Advertisements
Similar presentations
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Advertisements

Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
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.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
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.
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.
Pointers Contd.. Causing a Memory Leak int *ptr = new int; *ptr = 8; int *ptr2 = new int; *ptr2 = -5; ptr = ptr2; ptr 8 ptr2 -5 ptr 8 ptr2 -5.
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.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
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.
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.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
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.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
1 Chapter 15-2 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
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.
3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and each element except the last has.
Dynamic memory allocation and Pointers Lecture 4.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
C HAPTER 03 Pointers Compiled by Dr. Mohammad Alhawarat.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 3 – August 28, 2001.
Review 1 List Data Structure List operations List Implementation Array Linked List.
1 Final Exam Tues 3/16/10 (2-3:50) (Same classroom) Old Textbook - Chapters 11-16, 18 Focus is on 15, 16 and 18 Final Exam Tues 3/16/10 (2-3:50) (Same.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 Chapter 4 ADT Sorted List. 2 Sorted Type Class Interface Diagram SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem.
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.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Lecture.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
1 C++ Plus Data Structures Abstract Data Types Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Recap Resizing the Vector Push_back function Parameters passing Mechanism Primitive Arrays of Constants Multidimensional Arrays The Standard Library string.
Pointers and Dynamic Memory Allocation
Yan Shi CS/SE2630 Lecture Notes
Chapter 14 Dynamic Data and Linked Lists
Dynamic Storage Allocation
Introduction to Programming
CSC113: Computer Programming (Theory = 03, Lab = 01)
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
CSI 1340 Introduction to Computer Science II
Dynamic Memory.
C++ Plus Data Structures
Dynamic Memory CSCE 121.
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

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; x number ch

Obtaining Memory Addresses The address of a non-array variable can be obtained by using the address-of operator ‘&’ int x; float number; char ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number<<endl; cout << “Address of ch is “ << &ch << endl;

What is a Pointer Variable? A pointer variable is a variable whose value is the address of a location in memory To declare a pointer variable, you must specify the type of value that the pointer will point to. int *ptr; // ptr will hold the address of an int char *q; // q will hold the address of a char

Using a Pointer Variable int x; x = 12; int *ptr; ptr = &x; x ptr Because ptr holds the address of x, we say that ptr “points to” x

Unary operator * is the deference operator int x; x = 12; int *ptr; ptr = &x; cout << *ptr; x ptr The value pointed to by ptr is denoted by *ptr == *ptr

Using the deference operator int x; x = 12; int *ptr; ptr = &x; *ptr=5; cout << x; *ptr=5 changes the value at address ptr to x ptr

Another Example char ch; ch = ‘A’; char *q; q = &ch; *q = ‘Z’; char *p; p = q A Z ch q p

9 C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double

10 The NULL Pointer There is a pointer constant 0 called the “null pointer” denoted by NULL in cstddef. –But NULL is not memory address 0. –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. if (ptr != NULL) { … //ok to use *ptr here }

Allocation of Memory STATIC ALLOCATION Static allocation is the allocation of memory space at compile time. DYNAMIC ALLOCATION Dynamic allocation is the allocation of memory space at run time by using operator new.

Three Kinds of Program Data STATIC DATA: memory allocation exists throughout execution of program. –static long SeedValue; AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function. DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using unary operators new and delete

Using Operator new If memory is available in an area called the free store (or heap), operator new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. Otherwise, the null pointer 0 is returned. The dynamically allocated object exists until the delete operator destroys it.

Dynamically Allocated Data char *ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; ??? 2000 ptr

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; 2000 ptr

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; 2000 ptr ‘B’

Dynamically Allocated Data char* ptr; ptr = new char; *ptr = ‘B’; cout << *ptr; delete ptr; ??? 2000 ptr Delete deallocates the memory pointed to by ptr –The pointer is considered unassigned. The memory is returned to the free store.

Dynamic Arrays Array limitations –Must specify size first –May not know until program runs! Must ‘estimate’ maximum size needed –Sometimes OK, sometimes not –‘Wastes’ memory Dynamic arrays –Can grow and shrink as needed

Dynamic Array Allocation char *ptr; //ptr is a pointer variable that can hold //the address of a char ptr = new char[5]; //dynamically, during run time, allocates memory for 5 //characters and places into the contents of ptr their //beginning address ??? ptr 6000 ptr 6000

Dynamic Array Allocation char *ptr; ptr = new char[5]; strcpy(ptr, “Bye”); 6000 ptr 6000 ‘B’‘y’‘e’‘\0’ ptr[1] = ‘u’; 6000 ptr 6000 ‘B’‘u’‘e’‘\0’

Deleting Dynamic Arrays Allocated dynamically at run-time –So should be destroyed at run-time Use “delete [] ptr;” –De-allocates all memory for dynamic array –Brackets indicate ‘array’ is there

Memory Leak A memory leak occurs when dynamic memory (that was created using operator new) has been left without a pointer to it by the programmer, and so is inaccessible.

Causing a Memory Leak int *ptr = new int; *ptr = 8; int *ptr2 = new int; *ptr2 = -5; ptr = ptr2; ptr 8 ptr2 -5 ptr 8 ptr2 -5

A Dangling Pointer int *ptr = new int; *ptr = 8; int *ptr2 = new int; *ptr2 = -5; ptr = ptr2; ptr 8 ptr2 -5 Occurs when multiple pointers point to the same object and delete is applied to one of them.

Leaving a Dangling Pointer int *ptr = new int; *ptr = 8; int *ptr2 = new int; *ptr2 = -5; ptr = ptr2; ptr 8 ptr2 -5 delete ptr2; ptr2 = NULL; ptr 8 ptr2 NULL

Dynamic Array Example Sort an array of float numbers from standard input. The first element is the size of the array. For example: sortFromInput( ) { float *array; int size, idx; cin >> size; array = new float[size]; for (idx=0; idx<size; idx++) cin >> array[idx]; Sort(array, size); OutputSortedArray(array, size); delete[] array; } array idx=3 array