Download presentation
Presentation is loading. Please wait.
Published byDwayne Watson Modified over 6 years ago
1
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”
2
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
3
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
4
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 ?
5
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
6
Some Issues What happens if you try to assign a string/int/double expression to a pointer variable? e.g. what about q = ; ? 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
7
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.
8
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
9
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 = # // 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
10
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
11
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
12
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
13
Introduction to linked lists
node *p, *q; p = new node; p->num = 5; p->word = "Ali"; q p 5 Ali ? num word link ?
14
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 ?
15
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 ?
16
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
17
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
18
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.