R ECITATION #1 Pointer Basics by Müge Birlik. P ASS - BY - VALUE If you change the value of a parameter in function, corresponding argument does NOT change.

Slides:



Advertisements
Similar presentations
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Advertisements

Kernighan/Ritchie: Kelley/Pohl:
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
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.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
VBA Modules, Functions, Variables, and Constants
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Applications
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CS204 – Advanced Programming Pointers and Linked Lists Part 1: Basics.
Microsoft Visual C++.NET Chapter 61 Memory Management.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Announcements HW3 grades will be announced this week HW4 is due this week Final exam on August 25, 2010, Wednesday at 09:00 Duration is about 140 minutes.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers OVERVIEW.
C++ Memory Overview 4 major memory segments Key differences from Java
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
C HAPTER 03 Pointers Compiled by Dr. Mohammad Alhawarat.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
Review 1 List Data Structure List operations List Implementation Array Linked List.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Chapter Lists Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2010.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
P OINTERS A pointer is an address All data is stored in memory in some location that is indexed with an address Can refer to variables by name or by memory.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Dynamic Allocation in C
Introduction to Pointers and Dynamic Memory Allocation
Pointers Revisited What is variable address, name, value?
Dynamic Memory Allocation
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
7 Arrays.
Dynamic Memory.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

R ECITATION #1 Pointer Basics by Müge Birlik

P ASS - BY - VALUE If you change the value of a parameter in function, corresponding argument does NOT change in the caller function. Function works on the copy of the variable 2

P ASS - BY - VALUE One way to change the value of the parameter in the calling function is the following 3

P ASS - BY - REFERENCE If you change the value of a reference parameter in function, corresponding argument changes in the caller function. Function works on the actual variable, not on the copy 4

U NDERLYING M ECHANISMS For value parameters, the arguments’ values are copied into parameters. Arguments and parameters have different memory locations. 5

U NDERLYING M ECHANISMS For reference parameters, the parameter and the argument share the same memory location Parameter is an alias of the argument. 6

I NTRODUCING CONST Why do we use const? Guarantees safety of variable values. const assures that the value of the variable will not be changed. prevents accidental changes in the values of the variables. ! error C3892: 'pi' : you cannot assign to a variable that is const 7

I NTRODUCING CONST Why do we use const reference? For efficiency. For parameters that require a large amount of memory, making the copy takes time in addition to memory used for the copy. Reference parameters are not copied, and thus no extra memory is required, and less time is used. So, use const reference if the parameter require large amount of memory the value of the parameter will never be changed in the function 8

P OINTER B ASICS

W HY DO WE NEED POINTERS ? Pointers allow different sections of the code to share information easily. form the basis for implementing complex linked data structures, such as linked lists and binary trees. 10

W HAT IS A POINTER ? Pointers are variables that store an address in computer memory. This way, they simply store a reference to a variable. a pointer points to a dynamically allocated memory location (variable), not an ordinary variable. Lifetime of an ordinary variable is limited within its scope The code block in which it is defined After the block finishes, the variable returns back to the memory However, the lifetime of a dynamically allocated variable depends on the programmer. Special functions are used to allocate and free such variables; namely new and delete. 11

R EPRESENTATION OF A POINTER numPt r nu m 42 A simple int variable. The current value is the integer 42. This variable also plays the role of pointee for the pointer below. A pointer variable. The current value is a reference to the pointee num above (address)

S YNTAX OF POINTERS Pointer decleration: type *variable_name; Pointer variable is defined as a pointer having type of type. Pointer variable holds the address of a memory location that holds a type value. 13

S YNTAX OF POINTERS Dynamic memory allocation using new type *variable_name = new type ; allocates enough memory from heap (a special part of memory reserved for dynamic allocation) to store a type value. returns the address of this memory location. assign this address to a pointer variable for further processing. If type is a class, then class constructor is also invoked. 14

S YNTAX OF POINTERS You can have pointers for any type Primitive types (int, double, char,…) Built-in or user defined types, classes and structs (string, dice, date, …) Similarly, you can dynamically allocate memory for any type using the keyword new. 15

S YNTAX OF POINTERS Example (pointer definition for the Date class) a new Date object is created with value February 23, 2010 and date_ptr points to it. Example (pointer definition for vector class) a vector with 10 integer pointers, currently points nowhere. February 23, 2010 date_ptr 16

C AREFUL WITH NEW What is the problem with the following code segment? Error message: address of local variable returned! Returning a pointer to a statically allocated variable (with the & operator), is wrong! nSided no longer exists after the function returns. 17

C AREFUL WITH NEW Correct version 18

S YNTAX OF POINTERS Memory deallocation using delete delete variable_name; the memory location pointed by variable_name is returned back to the heap. this area now may be reallocated with a new statement. Problem: variable_name 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. e.g. p = NULL; NULL is a standard constant that you can directly use in your programs a NULL pointer means that it points nothing. 19

S YNTAX OF POINTERS You can only deallocate the memory spaces that have been dynamically allocated using new statement. Others (ordinary variables) are handled by the runtime system of the programming language. If you attempt to delete such a memory chuck, you will get core-dumped. 20

P ROBLEMS IN DEALLOCATION Careful ! deleting previously deallocated memory causes a crash. Question Do we need to delete p_temp? No. It points to a statically allocated (stack) variable. What happens if we delete? Most likely a crash or corrupt program, depending on the compiler. 21

P ROBLEMS IN DEALLOCATION : MEMORY LEAK Memory is not unlimited, make sure that you deallocate what you allocated Memory leak occurs when a computer program consumes memory but is unable to release it back to the operating system 22

P ROBLEMS IN DEALLOCATION : DANGLING PTR If multiple pointers point to same variable and one of them is deallocated, then rest of the pointers point to unallocated space. If you deallocate memory that a pointer points to, then it's pointing to garbage. Results are unpredictable Segmentation fault Returns garbage value 23

S YNTAX OF POINTERS Pointer dereference (follow the pointer) *variable_name To access the content/value of the memory location pointed by variable_name. 24

S YNTAX OF POINTERS The only restriction is that the pointer must point to some accessible memory location for the dereference operation to work. 25

S YNTAX OF POINTERS In the program, you can use dereference operator to manipulate the memory location as if it is a variable of the corresponding type. 26

S YNTAX OF POINTERS Pointer assignment A pointer can be assigned to another pointer of the same type. numPt r nu m numPtr 2 27

S YNTAX OF POINTERS Some issues regarding pointer assignment What happens if you try to assign a string/int/double expression to a pointer variable? e.g. what about numPtr = ; ? 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? a run-time (application) error occurs What happens if you display the value of a pointer? it displays the address 28

E XAMPLES 29

E XAMPLES Loop to allocate memory for each index of a vector and initialize to zero. 30

E XAMPLES 31 today tomorrow yesterday April x x544a8 April April April April April April April April April April x544a8 0x544a8

E XAMPLES 32 k sides roll count

R ECITATION #2 Advanced Pointer Stuff

S TRUCTS Used as data aggregates for an entity. Can store different types of variables/data e.g. Student struct may contain id,name,GPA,… Similar to classes, but everything is public do not have member functions Mostly used for combining data for an entity into a single structure. 34

S TRUCTS 35 Name and Lastname: John Coder ID:59 GPA:3.66

A RRAYS Arrays are collections of several elements of the same type. e.g. 100 integers, 20 strings, 125 students, 12 dates, etc. Single name is given to the entire array But each element is accessed separately a class-based version of arrays is the vector class. Arrays are homogeneous each element of an array has the same type this type must be specified at declaration 36

A RRAYS Items in an array are numbered those are called index numbering starts with 0 we have to use the index value to access an element of an array Syntax for declaring an array: type variable_name[element_count]; statically allocating an array indexdata

A RRAYS 38 January, 31 days February, 28 days March, 31 days April, 30 days May, 31 days June, 30 days July, 31 days August, 31 days September, 30 days October, 31 days November, 30 days December, 31 days

A RRAYS To dynamically allocate an array, specify the array size in square brackets [] after the type. type * variable_name = new type [element_count]; instead of hard-coding the size of the allocated array, you can also use a user-defined variable. 39

A RRAYS To delete a dynamically allocated array, you must include a pair of empty square brackets in the delete statement, just after the delete command. 40

B E CAREFUL WHILE USING NEW ! If there is not enough memory that can be allocated, then NULL pointer is returned. So, check whether the pointer is NULL or not after allocating. 41

2D A RRAYS Most common multidimensional array type Used to store data that is normally represented in a table format are homogeneous, similar to 1D arrays 42

2D A RRAYS Static allocation of 2D arrays Syntax for declaration type variable_name[row_count][column_count]; Accessing elements of a 2D array: variable_name[index1][index2]; 43 x x o o o x x o

2D A RRAYS Dynamic allocation of 2D arrays Syntax for declaration type ** variable_name; Memory allocation allocate memory for an array which contains a set of pointers next, allocate memory for each array which is pointed by the pointers 44

2D A RRAYS 45 dynamicArray X

2D A RRAYS 46 dynamicArray XXXXX

2D A RRAYS 47 dynamicArray

2D A RRAYS Deallocation of dynamically allocated 2D arrays Performed in reverse order 48

2D A RRAYS 49 dynamicArray

2D A RRAYS 50 dynamicArray XXXXX

2D A RRAYS 51 dynamicArray X

2D A RRAYS 52

P OINTER ARITHMETIC If you increment a pointer, it will be increased by the size of whatever it points to. Example in this case the pointer points to 4 bytes ahead to the next integer (note: integer is 4bytes long) 53

P OINTER ARITHMETIC QUESTION: What happens if you try to access *(ptr+10) ? You will get segmentation fault ! This memory location is not allocated. 54 s[0]s[1]s[2]s[3]s[4]s[5]S[6 ] s[7]s[8]s[9] *pt r *(ptr+2)*(ptr+9)

P OINTER ARITHMETIC 55 2nd one is often much more efficient !! -incrementing is faster than addition -also when array indexing is more complex (with more complicated offsets...), pointers are even more efficient

L INKED LISTS A linked list is a data structure that consists of nodes pointing to one another. Nodes can be represented using structs. 56 A1A1 A2A2 A3A3 A4A4

L INKED LISTS : INSERTING A NEW NODE Note that you should normally have a constructor for the struct; this is for illustration of the pointer usage. 57 5Ali numwor d next p

L INKED LISTS : INSERTING A NEW NODE Let’s add a new node to our linked list 58 5Ali numwor d next p q ?

L INKED LISTS : INSERTING A NEW NODE Let’s add a new node to our linked list 59 5Ali numwor d next p q ?? numwor d next ?

L INKED LISTS : INSERTING A NEW NODE Let’s add a new node to our linked list 60 5Ali numwor d next p q 8Veli numwor d next ?

L INKED LISTS : INSERTING A NEW NODE Let’s add a new node to our linked list 61 5Ali numwor d next p q 8Veli numwor d next

L INKED LISTS : ITERATING OVER A LINKED LIST 62 We use a temporary pointer to iterate over the list At each iteration, we set the temporary pointer to the next node We continue until there is no node left our temporary pointer becomes NULL 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next

L INKED LISTS : ITERATING OVER A LINKED LIST 63 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r

L INKED LISTS : ITERATING OVER A LINKED LIST 64 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r

L INKED LISTS : ITERATING OVER A LINKED LIST 65 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali

L INKED LISTS : ITERATING OVER A LINKED LIST 66 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali

L INKED LISTS : ITERATING OVER A LINKED LIST 67 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali

L INKED LISTS : ITERATING OVER A LINKED LIST 68 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali 8 Veli

L INKED LISTS : ITERATING OVER A LINKED LIST 69 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali 8 Veli

L INKED LISTS : ITERATING OVER A LINKED LIST 70 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali 8 Veli

L INKED LISTS : ITERATING OVER A LINKED LIST 71 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali 8 Veli 17 Ayşe

L INKED LISTS : ITERATING OVER A LINKED LIST 72 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali 8 Veli 17 Ayşe

L INKED LISTS : ITERATING OVER A LINKED LIST 73 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali 8 Veli 17 Ayşe

L INKED LISTS : ITERATING OVER A LINKED LIST 74 5Ali numwor d next p 8Veli numwor d next 17Ayşe numwor d next ite r 5 Ali 8 Veli 17 Ayşe

L INKED LISTS : REMOVING THE LIST 75 As linked list is allocated dynamically, it should be removed afterwards It is similar to iteration, but instead of printing out we remove each node using delete statement.

Thanks to Albert Levi and Berrin Yanıkoğlu 76