Programming in C/C Lecture 2

Similar documents
Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

Programming in C/C

Programming in C/C Lecture 3

Chapter 9. Pointers and Dynamic Arrays

Dynamic Memory Allocation and Linked Lists

Pointers and Dynamic Arrays

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Ch. 17: Linked Lists. Introduction to Linked Lists

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Programming in C/C

CSC 270 Survey of Programming Languages. What is a Pointer?

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Chapter 1: Object-Oriented Programming Using C++

What have we learned about when we learned about function parameters? 1-1

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Data Structures and Algorithms for Engineers

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

Data Structures and Algorithms for Engineers

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CSC 211 Intermediate Programming. Arrays & Pointers

6. Pointers, Structs, and Arrays. 1. Juli 2011

Homework Assignment #2 (revised)

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Lecture on pointers, references, and arrays and vectors

MM1_ doc Page E-1 of 12 Rüdiger Siol :21

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

1. Which of the following best describes the situation after Line 1 has been executed?

Pointers, Dynamic Data, and Reference Types

Lab Instructor : Jean Lai

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

Short Notes of CS201

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

CS201 - Introduction to Programming Glossary By

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

CS 161 Exam II Winter 2018 FORM 1

CS 240 Data Structure Spring 2018 Exam I 03/01/2018

Pointers and References

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

Linked List using a Sentinel

Lab # 02. Basic Elements of C++ _ Part1

Solution to CSE 250 Final Exam

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

BITG 1113: Function (Part 2) LECTURE 5

Computer Programming

CS24 Week 2 Lecture 1

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

Data Structure Series

ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers

CMSC 202 Midterm Exam 1 Fall 2015

Memory and C++ Pointers

Lectures 6/7 Pointers and Dynamic Arrays

Programming in C/C

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Exceptions, Case Study-Exception handling in C++.

Linked lists Tutorial 5b

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

A pointer variable has a pointer type, and holds pointer values. If a variable uses a number of adjacent locations, the address of the

Input And Output of C++

C++ Structures Programming Workshop 2 (CSCI 1061U)

Cpt S 122 Data Structures. Data Structures

Object-Oriented Programming for Scientific Computing

EE 109 Lab 8a Conversion Experience

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

6.096 Introduction to C++ January (IAP) 2009

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Lecture 16 More on Hashing Collision Resolution

Memory and Pointers written by Cathy Saxton

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

CS 376b Computer Vision

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Reference operator (&)

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

What is an algorithm?

a data type is Types

CS201 Some Important Definitions

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

2.1 Introduction UML Preliminaries Class diagrams Modelling delegation... 4

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Transcription:

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