Programming in C/C++ 2005-2006 Lecture 2 http://few.vu.nl/~nsilvis/c++/2006 Natalia Silvis-Cividjian e-mail: nsilvis@few.vu.nl vrije Universiteit amsterdam
News Check announcements on the C/C++ website 2
Topics variables and addresses pointers dynamic arrays linked lists self test exercices This lecture uses code from : W. Savitch, Problem solving with C++, Addison Wesley, 2005 Liberty Jones, Teach yourself C++ in 21 days, SAMS, 2005 3
Variables and addresses Each variable occupies a block of bytes in the memory, according to its type and the computer system. For example: int = 2 bytes, double = 4 bytes, char = 1 byte, array of 10 integers = 20 bytes, etc. The address of the first byte in the block is called the variable address (usually a hexadecimal number) and it is noted using the ampersand &. 4
Variables and addresses Similarity: a flat building with apartments of different size (2 rooms, 4 rooms). Postman looks for addresses. 5
Variables and addresses #include <iostream>; using namespace std ; void main() { int age = 14; double temperature = 38.5; ; cout << "the age value is= " << age ; cout << " and its address is " << &age << endl cout << "the temperature value is= " << temperature ; cout << " and its address is " << &temperature << endl ; } Output: the age value is 14 and its address is 0012FF7C the temperature value is 38.5 and its address is 0012FF74 6
Pointers: declaration A pointer is the memory address of a variable. pointer is a specific C/C++ variable type. when the pointer is declared, the variable he points to does not exist yet. C++ accepts also this notation: int* p ; 7
Define a pointer type Defines a pointer type : typedef int* intptr ; // defines a new type intptr as type pointer to int these two declarations are equivalent: int *p and intptr p ; Handy notation if you want to declare a few pointers of the same type. intptr p,q,r; instead of int *p, *q, *r ; 8
Pointers: assignment * is called dereferencing operator & is called address-of operator 9
Pointers: assignment 10
Dynamic variables: new operator A dynamic variable is created and destroyed while the program is running int *p ; p = new int ; creates a new dynamic integer variable and leaves p to point to this variable *p1 = 25 ; A non-dynamic variable is named automatic 11
Dynamic variables: delete operator Freestore (heap) is a special memory area reserved for dynamic variables. Take care: Recycle any freestore memory that is no longer needed using the delete operator: Otherwise : memory leak. delete p ; destroys the dynamic variable pointed by p After delete p, p becomes an undefined pointer variable: a dangling pointer. Take care: before using * again, be sure p points to something and is not a dangling pointer. Otherwise unpredictable effects. 12
Tips For every time in your program that you call new there should be a call to delete. After delete p and before trying *p, be sure p points to something 13
Dynamic arrays A dynamic array is an array whose size is not specified when you write the program. This size is determined when the program is running How to use a dynamic array? create a dynamic array typedef double* DoubleArrayPtr ; // declare a pointer type DoubleArrayPtr a ; //declare a pointer variable a = new double [10]; // create a dynamic array using new. use it like an ordinary array: a[0], a[1], etc. delete the array to return the memory to the freestore delete[] a ; // always use [ ]. 14
Linked lists A (singly) linked list is a dynamic data structure built from nodes which are connected by pointers 15
Linked lists Each node has always 2 fields: data (struct or class) and a pointer to the next node A list should always have: a head = a pointer to the first nod and an end-of-list marker = NULL 16
about NULL NULL is actually zero NULL is used to detect the end of a list included in different library headers: iostream, <cstddef> use: p = NULL ; pointer p points to nothing, where p can be any type of pointer 17
Example: a supermarket struct Node { string article_name ; int quantity ; string unit ; Node *next ; }; Node *head ; // head is a pointer //to a Node 18
Accessing Node Data (*head).article_name= Potato ; (*head).quantity = 50; head->article_name= Potato ; head->quantity = 50 ; 19
Linked lists manipulation How to: start a list insert a node at the head of the list search a linked list for a target insert a node at location inside a list remove a node from a list 20
How to start? struct Node { int data; Node *next ; }; Node *head ; head = new Node ; declare the type of each node create the first node as a dynamic variable (using new operator) let a pointer head point to this first node place the data in the first node make the next point to nothing (NULL) head->data = 20 ;; head->next = NULL ; Action: Start a list of integer numbers 21
Tip: use typedef in place of : Node *head ; use: typedef Node* NodePtr ; // define a type named NodePtr as // pointer to a Node NodePtr head ; 22
Insert a node at the head of a list Action: insert number 12 at the head of the list 23
Insert at the head of a list void head_insert (NodePtr& head, int the_number) { } NodePtr temp_ptr ; temp_ptr = new Node ; temp->data = the_number ; temp_ptr->next = head ; head = temp_ptr ; create a new node as a dynamic variable pointed by temp_ptr place data in this node make its next pointer point to the first node make the head pointer point to the new node 24
Advices avoid memory leaks. Always use a pointer to the head of the list. check your program also on empty lists. (here == NULL) 25
Searching a linked list Problem: design a function to search a target in a linked list The function returns a pointer to the first node that contains the target. If the target is not found the function will return NULL. (example: look for a book in a library on a messy shelf) Solution: the only way to move through a list is to follow the pointers we need a pointer to move through the list = iterator. Let s name it here. here starts from the head node while here is not pointing to a node containing the target and here is not the last node here jumps to the next node if the node pointed by here has the target, return here else return NULL. 26
Search a list Action: Search for number 15 27
Search a list NodePtr search (NodePtr head, int target) { NodePtr here = head ; if (here == NULL) return NULL ; else { while (here->data!= target && here ->next!= NULL) here = here->next ; if (here->data == target) return here ; else return NULL ; } 28
Insert at location Action: insert number 40 after the node pointed by after_me 29
Insert at location void insert (NodePtr after_me, int the_number) { NodePtr temp_ptr ; temp_ptr = new Node ; temp_ptr->data = the_number ; temp_ptr->next = after_me->next ; after_me->next = temp_ptr ; } 30
Remove a node from a list use two help pointers: discard to point to the node to be removed and before, to point to the node before the one to be deleted. before->next = discard->next. delete discard ; 31
Applications of linked lists 32
Self test exercises 1. What is wrong with this code? #include <iostream> using namespace std; int main() { int *p; *p=9; cout << The value at p: << *p ; return 0 ; } 33
Self test exercises 2. What is wrong with this code? #include <iostream> using namespace std; int main() { int *p; p = new int ; *p = 9; p = new int ; *p = 25 ; cout << The value at p: << *p ; return 0 ; } 34
Self test exercices 3. What is the output produced by the following code? int *p1,*p2 ; p1 = new int ; p2 = new int ; *p1 = 10 ; *p2 = 20 ; cout << *p1 << *p2 << endl ; p1 = p2 ; cout << *p1 << *p2 << endl ; *p1 = 30 ; cout << *p1 << *p2 << endl ; *p2 = *p1 ; cout << *p1 << *p2 << endl ; 35
Self test exercices 3. Suppose your program contains the following type definition and pointer declaration: struct Node { double data ; Node *next ; }; typedef Node* Pointer ; Pointer p1,p2; Suppose p1 points to a node of this type in a list. Write code to make p1 point to the next node in the list. 36
Self test exercise 4. Choose an answer and explain it: For a large array and large list holding the same type objects, inserting a new object at a know location into the middle of a linked list compared with the insertion in an array is: a) more efficient b) less efficient c) about the same d) dependant on the size of the two objects 37