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.

Slides:



Advertisements
Similar presentations
Chapter 6 Data Types
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
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 Types The type of a variable represents a set of values that may be assigned to the variable. For example, an integer variable is one that may take the.
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.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
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.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
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.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
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.
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.
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
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.
1 Data Structures CSCI 132, Spring 2014 Lecture 10 Dynamic Memory and Pointers.
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.
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.
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.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
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.
POINTERS.
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.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
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.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Pointers. What Is Pointer l every variable has memory address char c=’y’; int i=2; address of variable i is 0022 l address can used to refer to this variable.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Windows Programming Lecture 03. Pointers and Arrays.
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
Dynamic Storage Allocation
Pointers and Dynamic Arrays
Pointers.
Pointers Revisited What is variable address, name, value?
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Andy Wang Object Oriented Programming in C++ COP 3330
Dynamic Memory Allocation
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

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 size, at run time. We can use pointers for this! A pointer variable is a variable whose value is an address. Some programmers use the terms pointer and address interchangeably. Pointers allow us to manipulate data through its address This makes pointers very useful but also very dangerous.

2 Pointers How can pointers help? We request a memory block of a certain size The memory allocation function locates a suitable block (if one exists) and returns its starting address to us. We save that address in a pointer variable. We can now access any part of this block, indirectly, through the pointer/address. CAREFUL: When we are done with this memory, we must "return" it.

3 Intro to Pointers Example: address variable name, value 0xbfffc290:px, 0xbfffc294 x, -10 px is a pointer variable that contains the address of an integer variable, x. The value of px is address 0xbfffc294 The value of x is integer -10 We say that px points to x Because x is an int, we say that the base type of px is int 0xbfffc294: 0xbfffc298:

4 Intro to Pointers A pointer variable is declared as follows: base_type * variable_name ; the type of the object pointed to by the pointer the name of the pointer variable. It follows the same rules as regular variables, and usually starts with a p the asterisk signifies that this is a declaration of a pointer variable

5 Intro to Pointers Examples All of these variables are currently unitilialized int *pnum; // pnum will contain the address of an // integer float *ptemp; // ptemp will contain the address of a // floating point number char *pword, letter; // CAUTION! pword is a pointer // to char but letter is a char.

6 Initializing pointer variables There are several ways to initialize a pointer variable, depending on the intended use. Intention: We need a pointer to indirectly access an existing object. We can access the address of a variable by using the & operator. This is called the referencing operator. You can read it as "address of" int *px, x; px = &x; // px now points to x // Next, we'll see how to access x indirectly

7 Indirect access A pointer variable holds an address We can access the contents at that address by using the dereferencing operator, * Do not confuse this with the multiplication operator or with the asterisk used in the pointer's declaration. Example: int *px, x; px = &x; *px = 16; // go to address px ( 0xbfffc294 ) and put 16 there. cout << x << endl; // this prints 16 NEVER dereference an uninitialized pointer 0xbfffc290: px, 0xbfffc294 x, 16 0xbfffc294:

8 Initializing pointer variables There are several ways to initialize a pointer variable, depending on the intended use. Intention: We need a pointer to indirectly access an existing object. If that object is an array, just assign the array name to the pointer: We can do this, because an array name is the address of the first element of the array. The difference between an array and a pointer variable is that the array is a constant address. int list[5] = {10, 20, 30, 40, 50}; int *pnum; pnum = list; /* pnum now contains the address where list begins. In other words, it contains the address of the first element of the list. */

9 Initializing pointer variables There are several ways to initialize a pointer variable, depending on the intended use. Intention: We need a pointer to point to an array-like object whose size is determined at runtime. To do this, we must dynamically (i.e. at runtime) allocate as much memory as we need and set the pointer variable to contain the address where that memory chunk begins. Dynamic allocation is achieved with the new function. Furthermore, since the space is now allocated dynamically, we must take care to deallocate it when it is not needed any longer (otherwise, we'll have a so-called memory leak) Deallocation is achieved with the delete function.

10 Dynamic allocation int *pnums, size; cout << "How big a list do you want? "; cin >> size; pnums = new int [ size ] ; // note the brackets. // This allocates enough space to // hold size integers (i.e. 4*size bytes) delete [ ] pnums;// ALWAYS deallocate dynamically // allocated space to avoid memory leaks.

11 Dynamic allocation We can use new to allocate enough space for just one object. Example 1: Example 2: int *px; px = new int; // allocate enough space for one int *px = 15; // indirectly assign a value to that int delete px; // Note the lack of brackets int *px; px = new int(15); // allocate enough space for one int, and // initialize that int to 15. // Example 1 initialized the int through an // assignment. This example initializes it // through a constructor (more on constructors later). delete px;

12 Pointer arithmetic 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 type t will make the value of p equal to p+k*sizeof(t) Example: int *ptr = new int[3]; int *temp; temp = ptr + 2; // equivalent to temp = &(ptr[2]); delete [] ptr; 0x996100c: ? 0x : ? 0xbff2ebb4: ptr, 0x xbff2ebb0: temp, 0x x : ? 0x : ?

13 Basic operations allowed on pointers Referencing: &px returns the address where the pointer variable px is located. Dereferencing: *px returns the contents of the location pointed to by px Adding an integer: px+k, px-k returns the address px+k*sizeof(*px) or px-k*sizeof(*px) Equality: px == py, px != py compare two pointers for equality (sometimes) Relation: px py, px>=py ONLY WORKS WHEN px AND py POINT TO THE SAME OBJECT! Otherwise, it's undefined.

14 Pointer examples char *pletter, *pgrade; char grades[4] = {'A', 'B', 'C', 'D'}; char ch; pgrade = grades; /* pgrade points to the beginning of grades */ pletter = &ch; /* now, pletter points to variable ch */ pletter = pgrade; /* now, pletter points to the beginning of grades */ grades = pletter; /*ILLEGAL! The address of an array is constant! You cannot change its value */ pletter = 100; /* ILLEGAL! 100 is an integer, pletter's value should be an address */ pletter = &pgrade /* ILLEGAL! pletter should be the address of a char, but &pgrade is the address of a pointer (or, to be more specific, it's the address of the address of a char). The types do not match. */

15 NULL pointers NULL represents a special location in memory that is guaranteed to NOT contain valid data Dereferencing a NULL pointer will cause a segmentation fault. Programmers often initialize pointers to NULL to "catch" any unintended dereferencing of a pointer that does not contain valid data. GOOD IDEA! Always do this! new typically returns NULL if it fails to allocate memory.

16 delete Never try to deallocate the same memory twice Example: int *pnum, *pcopy; pnum = new int(32); pcopy = pnum; delete pnum; delete pcopy; // ERROR! This space has already been deallocated

17 delete The argument to delete should always be the address where the allocated space begins. Example: int *pnum, *pcopy; pnum = new int; pcopy = pnum; pnum ++; delete pnum; // ERROR! pnum does not point to the beginning of // the allocated space any longer. // delete pcopy; would be the correct way to // deallocate the space.