1 / 76

Recitation #1

Recitation #1. Pointer Basics by Müge Birlik. Pass-by-value. I f 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. Pass-by-value.

neith
Download Presentation

Recitation #1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Recitation #1 Pointer Basics by Müge Birlik

  2. Pass-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

  3. Pass-by-value • One way to change the value of the parameter in the calling function is the following

  4. Pass-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

  5. Underlying Mechanisms • For value parameters, the arguments’ values are copied into parameters. • Arguments and parameters have different memory locations.

  6. Underlying Mechanisms • For reference parameters, the parameter and the argument share the same memory location • Parameter is an alias of the argument.

  7. Introducing 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

  8. Introducing 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

  9. Pointer Basics

  10. Why 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.

  11. What 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.

  12. Representation of a pointer A simple int variable. The current value is the integer 42. This variable also plays the role of pointee for the pointer below. 0 42 num 1 2 3 4 5 1 numPtr A pointer variable. The current value is a reference to thepointee num above (address). 6 . . . .

  13. Syntax 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.

  14. Syntax 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.

  15. Syntax 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.

  16. February 23, 2010 date_ptr Syntax 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.

  17. Careful 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! • nSidedno longer exists after the function returns.

  18. Careful with NEW • Correct version

  19. Syntax 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.

  20. Syntax 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.

  21. Problems 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.

  22. Problems 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

  23. Problems 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

  24. Syntax of pointers • Pointer dereference (follow the pointer) • *variable_name • To access the content/value of the memory location pointed by variable_name.

  25. Syntax of pointers • The only restriction isthat the pointer must point to some accessible memory location for the dereference operation to work.

  26. Syntax 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.

  27. Syntax of pointers • Pointer assignment • A pointer can be assigned to another pointer of the same type. 0 num 42 1 2 3 4 numPtr 5 1 numPtr2 6 1 . . . .

  28. Syntax 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

  29. Examples

  30. Examples • Loop to allocate memory for each index of a vector and initialize to zero.

  31. Examples 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. Examples • k sides roll count • 0 1 1 1 • 1 3 3 1 • 5 2 1 • 7 4 1 • 4 9 1 1 • 5 11 4 1

  33. Recitation #2 Advanced Pointer Stuff

  34. Structs • 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.

  35. Structs Name and Lastname: John Coder ID: 59 GPA: 3.66

  36. Arrays • 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 arraysis the vector class. • Arrays are homogeneous • each element of an array has the same type • this type must be specified at declaration

  37. Arrays • 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 index data

  38. Arrays 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. Arrays • To dynamically allocate an array, specify the array size in squarebrackets [] 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.

  40. Arrays • To delete a dynamically allocated array, you must include a pair of emptysquare bracketsin the delete statement, just after the delete command.

  41. Be 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.

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

  43. 2D Arrays • 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]; x x o o o x x o

  44. 2D Arrays • 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

  45. 2D Arrays dynamicArray X

  46. 2D Arrays dynamicArray X X X X X

  47. 2D Arrays dynamicArray

  48. 2D Arrays • Deallocation of dynamically allocated 2D arrays • Performed in reverse order

  49. 2D Arrays dynamicArray

  50. 2D Arrays dynamicArray X X X X X

More Related