announcements hw3 grades will be announced this week hw4 is due this week final exam on august 25,...
TRANSCRIPT
AnnouncementsHW3 grades will be announced this weekHW4 is due this weekFinal exam on August 25, 2010, Wednesday at 09:00
Duration is about 140 minutes (+/- 10 minutes)Comprehensive but last topics will have more weight2 pages of cheat notes are allowedI will send classrooms later via email
Extra Recitations will be held next week before the finalI will make an announcement later about the final recitation times.
Introduction to Pointers and Dynamic Memory Allocation
Excerpts from Chapter 12some 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 topicsPointers 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 variablebut usually not an ordinary variable that we have used so fara 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 AllocationPointer and Dynamic Memory Allocation are two
different, but related conceptsa pointer stores the address of a dynamically allocated
memory locationIn C++ we have mechanisms
to create pointersto 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
Exampledouble *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 typedouble *q;q = p; // q and p points to the same location in memory
17.5p
17.5p
q
Some IssuesWhat happens if you try to assign a string/int/double
expression to a pointer variable?e.g. what about q = 123.45; ?
syntax errorWhat 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 occursLet’s see these cases in ptrdemo1.cppWhat happens if you display the value of a pointer?
have seen in ptrdemo1.cppit displays the address
The HeapA storage pool of available memory cells for dynamic allocation
only for dynamic allocationpointer variables and normal built-in variables and objects (int,
double, string, tvector, etc.) also use up memory, but not from the heapthey 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 finishesnew 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-allocateCAUTION: 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
ExampleDate *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 pointerstvector <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, 2009finalptr
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
deleteThe statement to de-allocate a memory location and
return to the heapdelete 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 usedmay 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 listsA linked list is a data structure where you create a list
of structs using pointersConsider the following struct definition
struct node{string word;int num;node *link; // pointer for the next node
};
node *p = new node;
? ?
num word link
p ?
Introduction to linked listsHow 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
? Ali
num word link
p ?
Introduction to linked lists
node *p, *q;
p = new node;
p->num = 5;
p->word = "Ali";
5 Ali
num word link
p
q
?
?
Introduction to linked lists
node *p, *q;p = new node;p->num = 5; p->word = "Ali";
q = new node;
5 Ali
num word link
p ? ? ?
num word link
?
q
?
Introduction to linked listsnode *p, *q;p = new node;p->num = 5; p->word = "Ali";
q = new node;q->num=8;q->word = "Veli";
5 Ali
num word link
p ? 8 Veli
num word link
?
q
?
Introduction to linked listsnode *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;
5 Ali
num word link
p ? 8 Veli
num word link
q
Linked ListsIn linked lists, we have several such nodes
connected to each otherinsertion, deletion, traversalcircular listsdoubly linked listsetc.will be covered in Data Structures course
End of CS 201End of CS 201Recitations byRecitations by Demet Y Demet Yıılmaz, Erman Pattuklmaz, Erman Pattuk
Hüseyin ErginHüseyin Ergin, Kubra Kalkan,, Kubra Kalkan, Kevser Karaca, Suheyla Cetin, Kevser Karaca, Suheyla Cetin,
Mehmet Mehmet ÇÇagragrıı ÇÇalpur,alpur, Onur Ahmet Durahim Onur Ahmet DurahimRecitation material prepared by Recitation material prepared by Albert Levi, Gülşen DemirözAlbert Levi, Gülşen DemirözHomework graded byHomework graded by Gozde Gul Isguder, Gozde Gul Isguder, Süleyman Kardaş Süleyman Kardaş
Homework prepared by Homework prepared by Berk TanerBerk Taner, Gülşen Demiröz, Gülşen DemirözExams prepared byExams prepared by Gülşen Demiröz Gülşen DemirözExams graded byExams graded by Demet YDemet Yıılmaz, Erman Pattuk, lmaz, Erman Pattuk,
Hüseyin ErginHüseyin Ergin,, Gozde Gul Isguder,Gozde Gul Isguder,Kubra Kalkan, Kevser Karaca, Kubra Kalkan, Kevser Karaca,
Mehmet Mehmet ÇÇagragrıı ÇÇalpur,alpur, Suheyla CetinSuheyla CetinOnur Ahmet DurahimOnur Ahmet Durahim,,Süleyman KardaşSüleyman Kardaş
Extra recitation supportExtra recitation support Demet Yilmaz, Huseyin Ergin Demet Yilmaz, Huseyin Ergin
Lectures byLectures by Gülşen DemirözGülşen Demiröz
Thanks to Albert Levi, Ersin Karabudak, Owen Astrachan, and all previous years’ Thanks to Albert Levi, Ersin Karabudak, Owen Astrachan, and all previous years’
CS201 assistants CS201 assistants
Special thanks to all of you for your time and effort in this courseSpecial thanks to all of you for your time and effort in this courseGood Luck in the final examGood Luck in the final exam
Copyright © 20Copyright © 20110, Sabanc0, Sabancıı University University