Introduction to Pointers and Dynamic Memory Allocation

Slides:



Advertisements
Similar presentations
Pointers.
Advertisements

Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
Kernighan/Ritchie: Kelley/Pohl:
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2006 Slide 1 Pointers by Jumail Bin Taliba Faculty of Computer.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CS204 – Advanced Programming Pointers and Linked Lists Part 1: Basics.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation 9.8.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Announcements HW3 grades will be announced this week HW4 is due this week Final exam on August 25, 2010, Wednesday at 09:00 Duration is about 140 minutes.
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 Data Structures CSCI 132, Spring 2014 Lecture 10 Dynamic Memory and Pointers.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
R ECITATION #1 Pointer Basics by Müge Birlik. P ASS - BY - VALUE If you change the value of a parameter in function, corresponding argument does NOT change.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Object Lifetime and Pointers
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers and Dynamic Arrays
Linked List :: Basic Concepts
Pointers.
Standard Version of Starting Out with C++, 4th Edition
Lectures linked lists Chapter 6 of textbook
Motivation and Overview
UNIT-3 LINKED LIST.
Pointers and Memory Overview
COMP 2710 Software Construction Pointers
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
CSCE 210 Data Structures and Algorithms
Lecture 6 C++ Programming
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
void Pointers Lesson xx
Dynamic Memory Allocation
Object Oriented Programming COP3330 / CGS5409
Pointers, Dynamic Data, and Reference Types
Pointers and Dynamic Variables
Scope Rules and Storage Types
Chapter 17: Linked Lists.
Let’s all Repeat Together
Homework Starting K&R Chapter 5 Good tutorial on pointers
Introduction to C++ Linear Linked Lists
CS150 Introduction to Computer Science 1
Dynamic Memory.
C Programming Lecture-8 Pointers and Memory Management
CS250 Introduction to Computer Science II
Data Structures & Algorithms
CS204 – Advanced Programming Pointers and Linked Lists Part 1: Basics
Standard Version of Starting Out with C++, 4th Edition
Dynamic Memory CSCE 121.
Classes and Objects Object Creation
LINEAR DATA STRUCTURES
Presentation transcript:

Introduction to Pointers and Dynamic Memory Allocation Excerpts from Chapter 12 some parts are not from book We will not cover everything about this concept (but we will finish the content in this ppt file) The rest will be mostly CS 202 and CS 204 topics Pointers are the base for linked “data structures”

Pointers and Dynamic Memory Allocation A pointer is a variable to store “address in computer memory” In this way, it points to a variable but usually not an ordinary variable that we have used so far a pointer points to (i.e. stores the address of) a dynamically allocated memory location (variable) The lifetime of such a dynamic location/variable depends on the programmer; we use special functions for dynamic memory allocation and freeing, namely new and delete However, the lifetime of an ordinary variable is defined by its scope the compound block in which the variable is defined after the block finishes, the variable returns back to the memory To sum up: Pointers and dynamic memory allocation allow us to manipulate the memory in a more flexible way

Pointers and Dynamic Memory Allocation Pointer and Dynamic Memory Allocation are two different, but related concepts a pointer stores the address of a dynamically allocated memory location In C++ we have mechanisms to create pointers to dynamically allocate memory (new statement) to make a pointer points to such a memory location (using assignment operator) to manipulate (change/access) the content of a memory location via pointers (* operator) to free dynamically allocated memory (delete statement) see next slides for the syntax and some examples

Syntax and examples - 1 Pointer declaration type *variable; variable is defined as a pointer of type type variable does not store a type value, but stores the address of a memory location that stores a type value Dynamic memory allocation using new statement new type; allocates enough memory from heap (a special part of memory reserved for dynamic allocation - will discuss later) to store a type value also returns the address of this memory location Need to assign this address to a pointer variable for further processing Example double *p; //a pointer for double type, but currently points nowhere p = new double; // memory is allocated to store a double value, but //currently not initialized. p now points to that location p ? p ?

Syntax and examples – 2 (See ptrdemo1.cpp) Accessing data with pointer *PointerVariable derefence or indirection operator. It means “the content of memory location pointed by PointerVariable” In the program, you can use this operator to manipulate the memory location as if it is a variable of the corresponding type *p = 17.5; // memory location pointed by p contains 17.5 cout << *p; // displays 17.5 A pointer can be assigned to another pointer of the same type double *q; q = p; // q and p points to the same location in memory p 17.5 q p 17.5

Some Issues What happens if you try to assign a string/int/double expression to a pointer variable? e.g. what about q = 123.45; ? syntax error What happens if you try to access a memory location pointed by a pointer that is not initialized? e.g. what about the following? double *q; cout << *q << endl; a run-time (application) error occurs Let’s see these cases in ptrdemo1.cpp What happens if you display the value of a pointer? have seen in ptrdemo1.cpp it displays the address

The Heap A storage pool of available memory cells for dynamic allocation only for dynamic allocation pointer variables and normal built-in variables and objects (int, double, string, tvector, etc.) also use up memory, but not from the heap they use the runtime stack (another pool of memory cells) automatically allocated when created and automatically de-allocated when the block in which it is declared finishes new statement allocates available memory from the heap, delete statement de-allocates and returns to the heap no automatic allocation and de-allocation; programmer decides when to allocate and de-allocate CAUTION: You have to have a pointer that points to a dynamically allocated memory location all the time; otherwise cannot be reached and deleted.

More on pointers and dynamic memory allocation You can have pointers for any type built-in or user-defined; classes and structs are also OK int, double, char, string, Robot, Dice, Date, … Similarly, you can dynamically allocate memory for any type i.e. you can use any type with new Example Date *finalptr = new Date(01, 22, 2009); a new Date object is created with value January 22, 2008 and finalptr points to it. You can have a vector/array of pointers tvector <int *> intptrs(10); a vector with 10 integer pointers, currently point nowhere Let’s write a loop to allocate memory for each of them and initialize to zero (see ptrdemo2.cpp) January 22, 2009 finalptr

Pointers to variables Can we have a pointer to point a variable that is not dynamically allocated but declared using regular techniques? yes, but you need to learn the address of such a variable using the & (address of) operator Such variables are not allocated from heap that is why their addresses are not close to dynamically allocated variables (run ptrdemo3.cpp) int num; int *ptr; num = 5; ptr = &num; // ptr contains the address of num; cout << *ptr << endl; What is output? 5, because ptr points to num’s location in memory Let’s see and run ptrdemo3.cpp for more details Generally a pointer is not used to point such variables

delete The statement to de-allocate a memory location and return to the heap delete PointerVariable; the memory location pointed by PointerVariable is now returned back to the heap; this area now may be reallocated with a new statement Problem: PointerVariable still points to the same location, but that location is no longer used may cause confusion, so it may be a good idea to reset the pointer to NULL (zero) after deleting. a NULL pointer means that it points nothing (terminating condition for linked lists that we will see in a moment) See and run ptrdemo4.cpp for details

Introduction to linked lists A linked list is a data structure where you create a list of structs using pointers Consider the following struct definition struct node { string word; int num; node *link; // pointer for the next node }; node *p = new node; p ? ? ? num word link

Introduction to linked lists How do you refer to a field in that struct? (*p).word = "Ali"; This is the same as writing p->word = "Ali"; (*PointerVariable). is the same as PointerVariable-> if PointerVariable is a pointer to a struct or a class How can you add another node that is pointed by p->link? see next slides and introlists.cpp p ? Ali ? num word link

Introduction to linked lists node *p, *q; p = new node; p->num = 5; p->word = "Ali"; q p 5 Ali ? num word link ?

Introduction to linked lists node *p, *q; p = new node; p->num = 5; p->word = "Ali"; q = new node; q p 5 Ali ? ? ? ? num word link num word link ?

Introduction to linked lists node *p, *q; p = new node; p->num = 5; p->word = "Ali"; q = new node; q->num=8; q->word = "Veli"; q p 5 Ali 8 Veli ? ? num word link num word link ?

Introduction to linked lists node *p, *q; p = new node; p->num = 5; p->word = "Ali"; q = new node; q->num = 8; q->word = "Veli"; p->link = q; q->link = NULL; q p 5 Ali 8 Veli ? num word link num word link

Linked Lists In linked lists, we have several such nodes connected to each other insertion, deletion, traversal circular lists doubly linked lists etc. will be covered in Data Structures course

End of CS 201 Recitations by Ahmet Demirelli, Aycan Adrian Çorum, Çağlar Tırkaz, Demet Yılmaz, Emine Dumlu, Erman Pattuk, Hüseyin Ergin, Mehmet Çelik, Mehmet Çagrı Çalpur, Muhsincan Şeşen, Burcu Özçelik, Can Yıldızlı, Onur Ahmet Durahim, Tevfik Hamdi Kitapçı Recitation material prepared by Albert Levi, Gülşen Demiröz Homework graded by Kevser Karaca, Osman Kiraz, Süleyman Kardaş Homework prepared by Berk Taner, Gülşen Demiröz Exams prepared by Gülşen Demiröz Exams graded by Burcu Özçelik, Can Yıldızlı, Demet Yılmaz, Erman Pattuk, Mehmet Çagrı Çalpur, Mostafa Safdari Shadloo. Muhsincan Şeşen,Onur Ahmet Durahim, Osman Kiraz,Süleyman Kardaş Extra recitation support Aycan Adrian Çorum, Can Yıldızlı, Muhsincan Şeşen,Tevfik Hamdi Kitapçı Lectures by Gülşen Demiröz Thanks to Albert Levi, Ersin Karabudak, Owen Astrachan, and all previous years’ CS201 assistants Special thanks to all of you for your time and effort in this course Good Luck in the final exam Copyright © 2010, Sabancı University