1 / 20

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types. Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays. floating. address. float double long double. pointer reference. C++ Data Types. simple.

ebranham
Télécharger la présentation

Pointers, Dynamic Data, and Reference Types

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. Pointers, Dynamic Data, and Reference Types • Review on Pointers • Reference Variables • Dynamic Memory Allocation • The new operator • The delete operator • Dynamic Memory Allocation for Arrays

  2. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool

  3. Addresses in Memory • In general, memory is byte addressable • At declaration, memory is allocated for a variable • How much? Depends on the data type • Address of first byte is the address of the variable int i; float f; char i; 200 201 202 203 … 500 … 700 701 702 703 • For an array, address of the first element is its address • Address-of-operator: & (for non-array variable) • &i gives address of i (= 200)

  4. c: p: &c ‘a’ char c = ‘a’; char *p = &c; Pointers • All addresses are integer values (but not of type int) • Pointer is a datatype whose value refers directly to (“points to”) another value stored at some memory location. • Declaration of pointer variable needs a type (why?) • For a type T, T* is the type “pointer to T” int *pi; // pointer to integer char *pc; // pointer to character float *pf; // pointer to floating point void *pv; // no type

  5. 5000 1000 i pi 20 1000 30 Operators & - Address of operator * - Dereferencing operator • & can be applied onto any variable • & on a pointer variable? (ex: &p where p is int *p;) • * can only be applied on pointer variable int i = 20; int *pi = &i; // pi points to i *pi = 30; // changes the value of i to 30 int i = 20, j = 10; int *pi = &i; // pi points to i int **ppi = π // ppi points to pi **ppi = 30; // changes the value of i to 30

  6. Arrays • For a type T, T[size] is the type “array of size elements of type T” • Elements are indexed from 0 … size-1 • [] operator references each element • Array name points to first element (i.e., 0th) (base address) • and it is a constant pointer int arr[4] = {10, 20, 30, 40}, i = 50; int *pi = &i; // pi points to i arr[0] = 11; // changes the first element // arr and &arr[0] gives the same value *arr = 12; // arr[0] changes to 12 arr = pi; // error: arr is a constant pointer pi = arr; // valid 100 104 108 112 arr : arr[2] arr[0] arr[1] arr[3] pi: 100

  7. Operations on pointers • Pointer assignment • Pointer arithmetic • Result of ++, --, +, - depends on pointer type • value of P+1 = value of P + sizeof (T) • Result of == is implementation-defined int v[5] = {1, 2, 3, 4, 0}; for (int i=0; v[i] != 0; i++) cout << v[i] << endl; int v[5] = {1, 2, 3, 4, 0}; int *p = v; for (; *p != 0; p++) cout << *p << endl; v[i] == *(v+i) int v[4], u[4]; int i1 = &v[2] - &v[0]; // i1 = 2 int i2 = &v[2] - &u[0]; // undefined

  8. Pointers and constants • const int *p;(same as int const *p;) • p is a pointer to integer which is a constant • int *const p; • p is a constant pointer to integer • Example: arr in int arr[10]; • Right-to-left reading of declarations int i = 10, j =20; const int *pi = &i; *pi = 30; // error: piis pointer to const pi = &j; // valid: pointer is not const int i = 10, j =20; int *const pi = &i; *pi = 30; // valid: piis pointer to variable pi = &j; // error: constant pointer

  9. 1000 pi: 1000 10 i: 11 r: References • Alternate names to variables • For type T, T&defines “reference to T” int i = 10; int &r = i; // r is reference to i r++; // same as i++ int *pi = &r; // same as &i • We can not have pointer to a reference • Hence, can not have array of references

  10. Usage of references • Can be specified as function arguments • Call-by-reference void increment ( int& rr ) { rr++; } int x = 1; increment (x); // x = 2 int &rr = x; rr++; • Can be used to define functions that can be used on both LHS and RHS of an assignment int arr[5] = {1, 2, 3, 4, 5}; // say, global array int & foo( int x ) { return arr[x]; } // return xth element foo(2)++; // increments arr[2]

  11. More power over the memory

  12. Dynamic Memory Allocation In C and C++, three types of memory are used by programs: • Static memory - where global and static variables live • Heap memory -dynamically allocated at execution time -"small" amount of “self-managed" memory accessed using pointers • Stack memory - used by automatic variables • Call stack or Function stack

  13. 3 Kinds of Program Data • STATIC DATA: Allocated at compiler time • DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete • AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function

  14. Dynamic Memory Allocation Diagram

  15. Dynamic Memory Allocation • In C, functions such as malloc() are used to dynamically allocate memory from the Heap. • void * malloc (size_t size); (explicit type cast required) • size bytes are allocated • In C++, this is accomplished using the new and delete operators • new is used to allocate memory during execution time • returns a pointer to the address where the object is to be stored • always returns a pointer to the type that follows the new

  16. Operator new Syntax new DataType new DataType [IntExpression] • If memory is available, new allocates the memory for requested object (or array) in heap, and returns a pointerto the memory allocated i.e., address of object (or first element) • Otherwise, program terminates with error message • The dynamically allocated object exists until the delete operator destroys it 16

  17. 1000 ptr: 1000 ‘B’ Operator new char *ptr; ptr = new char; // allocate memory for one character *ptr = ‘B’; cout << *ptr; pi: int *ptr; ptr = new int [4]; // memory for fourintegers ptr[0] = 10; ptr[1] = 20; … 100 100 104 108 112 • Dynamic memory has no variable names

  18. The NULLPointer • 0 can be used as constant of integral, floating-point, or pointer type (determined by context) • No object is allocated at address 0 • Hence, 0 is pointer literal • Can not dereference a NULL pointer GOOD BAD int *ptr = NULL; … if ( ptr != NULL ) { use ptr } int *ptr; … use ptr

  19. Operator delete Syntax int *ptr = new int; int *arr = new int [4]; … delete ptr; delete [] arr; arr = NULL; delete Pointer delete [ ] Pointer • The object or array currently pointed to by Pointer is deallocated, and the value of Pointer is undefined. The memory is returned to the free store (heap). • Good idea to set the pointer to the released memory to NULL • Square brackets are used with delete to deallocate a dynamically allocated array. 19

  20. Take Home Message • Be aware where a pointer points to, and what is the size of that space. • Have the same perspective in mind when you use reference variables. • Always check if a pointer points to NULL before accessing it (unless you are sure of it)

More Related