Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.

Slides:



Advertisements
Similar presentations
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Advertisements

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.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
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:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
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’;
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
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.
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.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Class 2 CSI2172
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
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.
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.
Stack and Heap Memory Stack resident variables include:
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
(continue) © by Pearson Education, Inc. All Rights Reserved.
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.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
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.
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 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.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Integer Types short month; // half of a machine word int car; // one machine word unsigned long distance; Character Types char c = ‘\0’; // one byte char.
Review 1 List Data Structure List operations List Implementation Array Linked List.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
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 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
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.
Slide 1 of 36. Attributes Associated with Every Variable Data type Data type Actual value stored in variable Actual value stored in variable Address of.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Windows Programming Lecture 03. Pointers and Arrays.
Yan Shi CS/SE2630 Lecture Notes
Introduction to Programming
Pointers and Memory Overview
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Dynamic Memory A whole heap of fun….
Dynamic Memory.
C Programming Lecture-8 Pointers and Memory Management
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Copyright 2005, The Ohio State University 1 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

Copyright 2005, The Ohio State University 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double

Copyright 2005, The Ohio State University 3 Addresses in Memory In general, memory is byte addressable At declaration, memory is allocated for a variable –How much? Depends on the data type –Address of first byte is the address of the variable int i; char i; float f; … 500 … For an array, address of the first element is its address Address-of-operator: & (for non-array variable) –&i gives address of i (= 200)

Copyright 2005, The Ohio State University 4 Pointers All addresses are integer values (but not of type int) Pointer is a datatype whose value refers directly to (“points to”) another value stored at some memory location. Declaration of pointer variable needs a type (why?) –For a type T, T* is the type “pointer to T” &c p: ‘a’ c:c: char c = ‘a’; char *p = & c; int *pi; // pointer to integer char *pc; // pointer to character float *pf; // pointer to floating point void *pv; // no type

Copyright 2005, The Ohio State University 5 Operators & can be applied onto any variable –& on a pointer variable? (ex: &p where p is int *p;) * can only be applied on pointer variable & - Address of operator * - Dereferencing operator int i = 20; int *pi = &i; // pi points to i *pi = 30; // changes the value of i to i pi int i = 20, j = 10; int *pi = &i; // pi points to i int **ppi = π // ppi points to pi **ppi = 30; // changes the value of i to 30

Copyright 2005, The Ohio State University 6 Arrays For a type T, T[size] is the type “array of size elements of type T” Elements are indexed from 0 … size-1 [] operator references each element Array name points to first element (i.e., 0 th ) (base address) –and it is a constant pointer int arr[4] = {10, 20, 30, 40}, i = 50; int *pi = &i; // pi points to i arr[0] = 11; // changes the first element // arr and &arr[0] gives the same value *arr = 12; // arr[0] changes to 12 arr = pi; // error: arr is a constant pointer pi = arr; // valid arr : arr[0] arr[1] arr[2] arr[3] pi: 100

Copyright 2005, The Ohio State University 7 Operations on pointers Pointer assignment Pointer arithmetic  Result of ++, --, +, - depends on pointer type  value of P+1 = value of P + sizeof (T)  Result of == is implementation-defined int v[5] = {1, 2, 3, 4, 0}; for (int i=0; v[i] != 0; i++) cout << v[i] << endl; int v[5] = {1, 2, 3, 4, 0}; int *p = v; for (; *p != 0; p++) cout << *p << endl; v[i] == *(v+i) int v[4], u[4]; int i1 = &v[2] - &v[0]; // i1 = 2 int i2 = &v[2] - &u[0]; // undefined

Copyright 2005, The Ohio State University 8 Pointers and constants const int *p; (same as int const *p;) –p is a pointer to integer which is a constant int *const p; –p is a constant pointer to integer –Example: arr in int arr[10]; Right-to-left reading of declarations int i = 10, j =20; const int *pi = &i; *pi = 30; // error: pi is pointer to const pi = &j; // valid: pointer is not const int i = 10, j =20; int *const pi = &i; *pi = 30; // valid: pi is pointer to variable pi = &j; // error: constant pointer

Copyright 2005, The Ohio State University 9 References Alternate names to variables For type T, T& defines “reference to T” int i = 10; int &r = i; // r is reference to i r++; // same as i++ int *pi = &r; // same as &i  We can not have pointer to a reference  Hence, can not have array of references i: pi: r: 11

Copyright 2005, The Ohio State University 10 Usage of references Can be specified as function arguments –Call-by-reference void increment ( int& rr ) { rr++; } int x = 1; increment (x); // x = 2 int &rr = x; rr++; Can be used to define functions that can be used on both LHS and RHS of an assignment int arr[5] = {1, 2, 3, 4, 5}; // say, global array int & foo( int x ) { return arr[x]; } // return xth element foo(2)++;// increments arr[2]

Copyright 2005, The Ohio State University 11 More power over the memory

Copyright 2005, The Ohio State University 12 Dynamic Memory Allocation Static memory - where global and static variables live Heap memory -dynamically allocated at execution time -"small" amount of “self- managed" memory accessed using pointers Stack memory - used by automatic variables –Call stack or Function stack In C and C++, three types of memory are used by programs:

Copyright 2005, The Ohio State University 13 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

Copyright 2005, The Ohio State University 14 Dynamic Memory Allocation Diagram

Copyright 2005, The Ohio State University 15 Dynamic Memory Allocation In C, functions such as malloc() are used to dynamically allocate memory from the Heap. –void * malloc (size_t size); (explicit type cast required) –size bytes are allocated 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

Copyright 2005, The Ohio State University Operator new Syntax new DataType new DataType [IntExpression] If memory is available, new allocates the memory for requested object (or array) in heap, and returns a pointer to the memory allocated i.e., address of object (or first element) Otherwise, program terminates with error message The dynamically allocated object exists until the delete operator destroys it 16

Copyright 2005, The Ohio State University 17 Operator new char *ptr; ptr = new char; // allocate memory for one character *ptr = ‘B’; cout << *ptr; 1000 ptr: ‘B’  Dynamic memory has no variable names pi: 100 int *ptr; ptr = new int [4]; // memory for four integers ptr[0] = 10; ptr[1] = 20; …

Copyright 2005, The Ohio State University 18 The NULL Pointer 0 can be used as constant of integral, floating-point, or pointer type (determined by context) No object is allocated at address 0 –Hence, 0 is pointer literal Can not dereference a NULL pointer int *ptr; … use ptr int *ptr = NULL; … if ( ptr != NULL ) { use ptr } BAD GOOD

Copyright 2005, The Ohio State University 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 (heap). Good idea to set the pointer to the released memory to NULL Square brackets are used with delete to deallocate a dynamically allocated array. 19 int *ptr = new int; int *arr = new int [4]; … delete ptr; delete [] arr; arr = NULL;

Copyright 2005, The Ohio State University 20 Take Home Message Be aware where a pointer points to, and what is the size of that space. Have the same perspective in mind when you use reference variables. Always check if a pointer points to NULL before accessing it (unless you are sure of it)