1 Working with Pointers An exercise in destroying your computer.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Linked Lists Geletaw S..
COMP171 Fall 2005 Lists.
DATA STRUCTURES USING C++ Chapter 5
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
An introduction to pointers in c
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
Linked Lists
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.
CS 106 Introduction to Computer Science I 12 / 04 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
C++ Classes and Data Structures Jeffrey S. Childs
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Pointers OVERVIEW.
Linked Lists part 2 CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University.
Object-Oriented Programming in C++
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
1 Workin’ with Pointas An exercise in destroying your computer.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Copyright © 2002 Pearson Education, Inc. Slide 1.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 11 – Data Structures.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
1 Chapter 6 Methods for Making Data Structures. 2 Dynamic Arrays in Data Structures In almost every data structure, we want functions for inserting and.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
1 CSC 211 Data Structures Lecture 11 Dr. Iftikhar Azim Niaz 1.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Data Structure & Algorithms
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
CS32 Discussion Section 1B Week 3 TA: Hao Yu (Cody)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 17: Linked Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 18: Linked Lists.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Popping Items Off a Stack Using a Function Lesson xx
Pointers and Linked Lists
Copy Constructor / Destructors Stacks and Queues
CS 1114: Implementing Search
Dr. Bernard Chen Ph.D. University of Central Arkansas
CSCI 3333 Data Structures Linked Lists.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Pointers and Linked Lists
Popping Items Off a Stack Lesson xx
Introduction to C++ Linear Linked Lists
Data Structures & Algorithms
Presentation transcript:

1 Working with Pointers An exercise in destroying your computer

2 What is this? Your worst nightmare! Comes from pointer misuse

3 Let’s look at Memory! Let’s look at Memory! Blue is memory address, Black is value

4 Declare an int int myInt; myInt

5 What’ve we done? By declaring the int, we’ve taken up just enough memory to hold an int We don’t know where in memory (the address) that it’s located Computer picks “at random” What value is at that memory location? Can we print that value out? –The value –4717 would print! (garbage)

6 Copy 42 into that Section of Memory myInt = 42; myInt

7Pointers Allow us to get to the address of where information is located Similar to call forwarding –Ask the pointer where to go –Go there for the information To create a pointer, we use the * Follows format of ; Example: int* ptr;

8 Declare an int pointer int* ptr; ptr myInt

9 Now what have we done? Created a new variable of type ptr that points to an int Notice that we haven’t initialized the pointer to “point” to myInt yet What if we print the pointer out?

10 cout << ptr; cout << ptr; (prints out value of ptr: 98131) ptr myInt

11 Problem How do we get address of myInt so ptr can point to it? Remember, we can still access the value of myInt directly int someInt = myInt; We really need the pointer to store the address of where myInt is located We do not need to store the value of myInt for the pointer (just the address)

12 The & operator Use the & operator to get the address of where the variable is in memory What would the following statement print to the screen? cout << &myInt << endl;

13 What would happen? cout << &myInt; ptr myInt

14 Getting the Pointer to Point We now need “ptr” to point to myInt Code: ptr = &myInt; ptr is a pointer, so it expects an address to be assigned to it Here, we get the address of where myInt is stored in memory and copy that value into “ptr”

15 Before ptr myInt

16 After ptr = &myInt; ptr myInt

17 What would this do? ptr = myInt; ptr myInt

18 Wrong Address ptr = myInt; ptr myInt

19 Tricky Screens of Death! Last thing to learn is how to “de-reference” a pointer This means “how to follow the pointer” Unfortunately, we use the * operator as well Example: cout << *ptr << endl; Follow wherever ptr is pointing to and print that value out.

20 Follow the Pointer and Print it Out cout << *ptr << endl; ptr myInt

21 Another Example Another Example Blue is memory address, Black is value, Red is variable name

22 Declare a Pointer int *ptr; ptr

23 What would happen? cout << *ptr << endl; ptr

24 Blue Screen of Death!

25 Because parameter passing only passes a copy so the function can’t change main’s variables! void cannotChange (int x) { x = 6; cout << x << endl; } void main ( ) { int myInt = 17; cannotChange (myInt); cout << myInt << endl; } Why do I need Pointers?

26 Because parameter passing only passes a copy so the function can’t change main’s variables! void cannotChange (int x) { x = 6; cout << x << endl; } void main ( ) { int myInt = 17; cannotChange (myInt); cout << myInt << endl; } Declare myInt myInt

27 Because parameter passing only passes a copy so the function can’t change main’s variables! void cannotChange (int x) { x = 6; cout << x << endl; } void main ( ) { int myInt = 17; cannotChange (myInt); cout << myInt << endl; } Call the function myInt

28 Because parameter passing only passes a copy so the function can’t change main’s variables! void cannotChange (int x) { x = 6; cout << x << endl; } void main ( ) { int myInt = 17; cannotChange (myInt); cout << myInt << endl; } Here’s where the Copy is Made myInt x

29 Because parameter passing only passes a copy so the function can’t change main’s variables! void cannotChange (int x) { x = 6; cout << x << endl; } void main ( ) { int myInt = 17; cannotChange (myInt); cout << myInt << endl; } Changing Only Local Copy myInt x

30 Because parameter passing only passes a copy so the function can’t change main’s variables! void cannotChange (int x) { x = 6; cout << x << endl; } void main ( ) { int myInt = 17; cannotChange (myInt); cout << myInt << endl; } Print Out Local Copy (6) myInt x

31 Because parameter passing only passes a copy so the function can’t change main’s variables! void cannotChange (int x) { x = 6; cout << x << endl; } void main ( ) { int myInt = 17; cannotChange (myInt); cout << myInt << endl; } Return to Main (print 17) (x is gone and leaves garbage) myInt

32 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Now with Pointers

33 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Declare myInt myInt

34 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Declare a Pointer to myInt myInt ptr

35 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Pass a Copy of ptr myInt ptr

36 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Pass a Copy of ptr myInt ptr x

37 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Change Whatever x is Pointing too myInt ptr x

38 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Change Whatever x is Pointing too myInt ptr x

39 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Follow x and Print it Out (6) myInt ptr x

40 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } See the Change in main (6 also) myInt ptr x

41 void canChange (int* x) { *x = 6; cout << *x << endl; } void main ( ) { int myInt = 17; int* ptr = &myInt; canChange (ptr); cout << myInt << endl; } Interesting Note At this point, these two statements print out the same thing! cout << *ptr << endl; cout << myInt << endl So do these! cout << ptr << endl; cout << &myInt << endl; WHY?

42 Summary of Pointers To understand pointers, you need to understand memory The & is the secret to it all! Create and de-reference with * Passing a pointer to a function can make changes to the main

Lists, Linked Lists, Stacks, and Queues

A List is a collection of data elements in an array structure. From any given element in the array, the previous and next items can be obtained by moving to adjacent memory locations. A Linked List is a collection of data elements where the location of each element in memory is only recorded by a pointer from a previous element. The data elements may happen to be adjacent in memory, but you cannot rely on this. What the is a Linked List?

List : (Array of 5 elements : simple integers) Linked List : (5 elements - all simple integers)

–Are just a sequence of data linked together in memory. –Each element in the list is made up of data plus a pointer to the next element in the list. –Node is the common name used for this data plus the associated pointer to the next item in the list. –However, many kilo-bytes of data : names, addresses, student-ids, etc - could be stored at each Node. –A chain is only as strong as its weakest link. –Similarly, if something erased or corrupted a Node in the middle of the list, then Nodes after this will NOT be found ! What the is a Linked List?

Queues : FIFO Vs LIFO Queues can be of two main types : –FIFO - First In First Out The first item into the queue is the first to be processed or output. Example : Supermarket checkout queue. –LIFO queue - Last In First Out. The last item into the queue is the first one out. Example : Stack of paper - where you put paper on top of each other and can only get to a page in the stack by removing each page on top of it in turn.

Linked Lists - All are LIFO in this Lecture We are going to build all Linked Lists in this lecture on a LIFO queue, but we could have made them all FIFO instead. Exercise : As an exercise that will help you understand queues and Linked Lists, you can convert these examples to FIFO.

Building a Basic Linked List #include // for cin and cout. #include // for NULL. #include // getchar // Define the type of data to be stored at each node typedef float ListElement; struct Node { ListElement Value;// Data stored at this Node Node* Next;// Pointer to Next Node in the List };

Basic Linked List - only 4 Functions class Linked_List { private: Node *First; public: Linked_List(); // Constructor // Add Node into the start of a Linked List void Insert_Node (ListElement In_Value); };

Basic Linked List - Diagram Once we have setup the class member functions and created a main() program to use our Linked List class, our Linked List could be visualized as : Value 3 Next First NULL Value 1 Next Value 2 Next

Basic Linked List - Constructor Linked_List::Linked_List() // Constructor { // Create an empty list First = NULL; }

Basic Linked List - Insert Node void Linked_List::Insert_Node (ListElement In_Value) // Add Node into the start of a Linked List. { Node *New_Node = new Node; // Store the value of the node. New_Node->Value = In_Value; // The Next Node in the list is currently the First Node. New_Node->Next = First; // Make our new node the new First Node. First = New_Node; }

Basic Linked List - Overloaded Output << Operator ostream& operator << (ostream& out, const Linked_List& My_List) { Node *Curr_Node; Curr_Node = My_List.First; // Loop through all nodes in the list. while (Curr_Node != NULL) { out Value; // Display each Node's Value Curr_Node = Curr_Node->Next; // Point at the next node in the list } out << endl; return out; }

Basic Linked List - simple Main program void main() { Linked_List My_List; // Define a Linked List My_List.Insert_Node (1.1); // Add in a bunch of nodes My_List.Insert_Node (2.2); My_List.Insert_Node (3.3); cout << "\n" << My_List; // Display the list }

Basic Linked List - What really is happening? Declaring the Linked List :Linked_List My_List; Would simply set First to NULL, so we have a pointer pointing at the null memory address. Inserting the first node :My_List.Insert_Node (1.1); Inserting the second node :My_List.Insert_Node (2.2); 1.1 Next First NULL 2.2 Next First NULL 1.1 Next

Linked Lists - Find All Nodes with a particular Value void Linked_List::Find_Nodes_With_Value (ListElement In_Value) // Find ALL Nodes in a Linked List with a particular value stored in them. { // Allocate a working Node. Node *Curr_Node = First; int Node_Count = 0; // Keep track of the number of Nodes found. // Skip through the Linked List and list all nodes we find with the required value. cout << "\nNodes with value of " << In_Value << " : ";

Linked Lists - Find All Nodes with a particular Value while (Curr_Node != NULL) { Node_Count++; if (Curr_Node->Value == In_Value) cout << Node_Count << ", "; Curr_Node = Curr_Node->Next; } if (Node_Count == 0) cout << "No Nodes Found !!"; cout << endl; }

Linked Lists - Find All Nodes with a particular Value Example Usage : Find_Nodes_With_Value (3.3); will display all Nodes in the linked list with a value of 3.3. If none are found, a “None Found” message will be displayed.

Linked Lists Delete a Node from the List We will now look at a function to delete a particular node in the list. Remember: –When we insert a new node, it is our new FIRST node. –We have a LIFO queue - Last In First Out. –So, when we delete node number 1, we are actually deleting the first node in the list, which is the node most recently added to the list!

Linked Lists Delete a Node from the List void Linked_List::Delete_Node (unsigned int Node_Num) // Delete a Node from a Linked List. { // Allocate Del and Prev Nodes. Node *Del_Node = First; Node *Prev_Node = First; // Skip through the Linked List to get to the required node. for (int i = 1; i < Node_Num; i++) { if (Del_Node->Next == NULL) // Stop when there are no more nodes. break; Prev_Node = Del_Node; Del_Node = Del_Node->Next; }

Linked Lists Delete a Node from the List // Make sure we are deleting a valid Node. if (Node_Num > 0) { if (Node_Num == 1) // If we are deleting the first node, make First point at the second // node in the list. First = Del_Node->Next; else // Point the previous node to the node after the one to be deleted. Prev_Node->Next = Del_Node->Next; // Delete the required Node. delete Del_Node; }

Linked Lists Delete a Node from the List Delete_Node (0) will delete nothing. There is not a 0’th node number in the list. Delete_Node (1) will delete the first node in the list. (i.e. the last node inserted into the list, since nodes are inserted at the start of the list by the Insert function. Remember : LIFO! Delete_Node (2) will delete the second node. (i.e. the second last node inserted into the list).

Linked Lists Delete a Node from the List Delete_Node (50) will delete the last node if there are 50 nodes in the list. (i.e. the very first node inserted into the list). Delete_Node (99) when there are only 50 nodes in the list will delete the last node in the list. (i.e. the very first node inserted into the list).

Some Points on Linked Lists When working with pointer data structures (such as Linked Lists) it is important that you use diagrams when developing or interpreting code, even experienced code writers make logic errors. Be very careful when inserting or deleting nodes so that links between nodes are not broken. It is crucial that you ensure your code works with all nodes - especially the first and last nodes in the list.

Generic Linked List Class Let’s start of with an extremely basic class - called Animals. Then, we will include this class in a Liked List class, and use the member functions of our Animals class to do any of the input / output for Animals. In this way, by changing a single line of code in our Linked List class, we can make our Linked List work with any kind of data in any kind of class.

Generic Linked List - Animals Class Header class Animal { private: float Height; char Name[30]; int Age; public: Animal(); // Constructor. };

Generic Linked List - Animals Class Member Functions Animal::Animal()// Constructor. { Anim_Height = 0; Anim_Name [0] = '\0'; Anim_Age = 0; }

Generic Linked List - Basic Linked List Class Header typedef Animal List_Element; struct Node { List_Element Value;// We are now storing Animals data Node* Next; }; class Linked_List { private: Node *First; public: Linked_List(); // Constructor. void Insert_Node (); };

Generic Linked List - Basic Linked List Class Member Functions Linked_List::Linked_List()// Constructor. (Same as earlier in Lecture) { // Create an empty list. First = NULL; }

Generic Linked List - Basic Linked List Class Member Functions void Linked_List::Insert_Node () // Add Node into the start of a Linked List { // Allocate New Node. Node *New_Node = new Node; // Get and store the value of the new node. // The Next Node in the list is the current First Node. New_Node->Next = First; // Make our new node the new First Node. First = New_Node; }

Generic Linked List - Main Program void main() { Linked_List My_List; // Define a Linked List - of Animals My_List.Insert_Node (); // insert an item in the list cout << "\n\n" << My_List;// Display the list }

Classes of Classes We have a class (Animals) which has private data and various member functions. Then, we have included this in a Linked List class, with its own private data and its own member functions. When C++ notices that we are manipulating the Linked List, then the Linked Lists functions are called. If any of these Linked List functions manipulate any Animals data, then the Animals functions are called automatically by C++.

In exactly this way, classes can be combined and extremely complex systems can be built, and at each level there are member functions doing their job on the private data of the class they belong to. Some of the most complex human creations are built like this, for example : –Operating Systems –Games –Business Applications –Network Software Classes of Classes

Very Brief Introduction to Stacks and Queues Stacks and Queues are both special types of data structures or ADTs that may be implemented as linked lists or using an array. These ADTs are very useful for many different type of programming problems. A stack’s data : o is always added (pushed) onto the front of the list / array, and, o removed (popped) from the front of the list / array. This type of data structure is called a Last In First Out (LIFO) structure. That is the last item added is the first removed.

Stack as a linked list To get to a particular number in the stack, we would need to keep removing values off the top of the stack until we got to the required value.

In contrast, a queue’s data : –is always added onto the end of the list, and, –removed from the front of the list. This type of data structure is called a First In First Out (FIFO) structure. Just like a queue at a super-market checkout or a bank Queues

Queue as a linked list To get to a particular number in the queue, we would need to keep removing values off the queue (i.e. to the left) until we got to the required value.

79 End of Lecture Next time, lists continued…