Download presentation
Presentation is loading. Please wait.
Published byRodney Bennett Modified over 9 years ago
1
R ECITATION #1 Pointer Basics by Müge Birlik
2
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
3
P ASS - BY - VALUE One way to change the value of the parameter in the calling function is the following 3
4
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
5
U NDERLYING M ECHANISMS For value parameters, the arguments’ values are copied into parameters. Arguments and parameters have different memory locations. 5
6
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
7
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
8
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
9
P OINTER B ASICS
10
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
11
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
12
R EPRESENTATION OF A POINTER........ 0 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). 1 2 3 4 5 6 1 12
13
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
14
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
15
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
16
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
17
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
18
C AREFUL WITH NEW Correct version 18
19
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
20
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
21
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
22
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
23
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
24
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
25
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
26
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
27
S YNTAX OF POINTERS Pointer assignment A pointer can be assigned to another pointer of the same type. numPt r nu m........ 0 42 1 2 3 4 5 6 1 1 numPtr 2 27
28
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 = 123.45; ? 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
29
E XAMPLES 29
30
E XAMPLES Loop to allocate memory for each index of a vector and initialize to zero. 30
31
E XAMPLES 31 today tomorrow yesterday April 13 2000 0x54490 0x544a8 April 13 2000 April 14 2000 April 12 2000 April 13 2000 April 12 2000 April 12 2000 April 13 2000 April 14 2000 April 14 2000 April 13 2000 0x544a8 0x544a8
32
E XAMPLES 32 k sides roll count 0 1 1 1 1 3 3 1 2 5 2 1 3 7 4 1 4 9 1 1 5 11 4 1
33
R ECITATION #2 Advanced Pointer Stuff
34
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
35
S TRUCTS 35 Name and Lastname: John Coder ID:59 GPA:3.66
36
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
37
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 37 061023 1100238 227390 323975 4102974 55482 698214 767782 869821 967762 indexdata
38
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
39
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
40
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
41
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
42
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
43
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
44
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
45
2D A RRAYS 45 dynamicArray X
46
2D A RRAYS 46 dynamicArray XXXXX
47
2D A RRAYS 47 dynamicArray
48
2D A RRAYS Deallocation of dynamically allocated 2D arrays Performed in reverse order 48
49
2D A RRAYS 49 dynamicArray
50
2D A RRAYS 50 dynamicArray XXXXX
51
2D A RRAYS 51 dynamicArray X
52
2D A RRAYS 52
53
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
54
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)
55
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
56
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
57
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
58
L INKED LISTS : INSERTING A NEW NODE Let’s add a new node to our linked list 58 5Ali numwor d next p q ?
59
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 ?
60
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 ?
61
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
62
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
63
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
64
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
65
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
66
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
67
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
68
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
69
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
70
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
71
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
72
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
73
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
74
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
75
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.
76
Thanks to Albert Levi and Berrin Yanıkoğlu 76
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.