Presentation is loading. Please wait.

Presentation is loading. Please wait.

References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team Telerik.

Similar presentations


Presentation on theme: "References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team Telerik."— Presentation transcript:

1 References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team http://academy.telerik.com Telerik Software Academy

2 1. References and their Applications 2. Pointers and Memory 3. Working with Pointers  Referencing & Dereferencing  Pointer arithmetic 4. Pointers vs. References 5. Pointers and Arrays 6. C++ Memory and Storage Types 7. Working with Dynamic and Static Memory 2

3 Variables aliases, Passing references to functions

4  A variable indicates a chunk of memory  Computer perceives the variable as that chunk  References are aliases of variables  Same type, same memory, different name  i.e., indicate same chunk of memory as the variable  A reference only represents one variable  Through its lifetime  Must be initialized immediately (on declaration)

5  Syntax for defining a reference to a variable  Reference points to same memory as its variable:  Its value is the value of the variable  Assigning the reference a value will actually assign the variable a value int v = 5; int &r = v; cout<<r<<endl; //prints 5 v = 6; cout<<r<<endl; //prints 6 r = 4; cout<<v<<endl; //prints 4 cout<<r<<endl; //prints 4 int &r = someVar; //reference to variable named //someVar (already existing) //someVar (already existing) '&' denotes a reference Initialization is obligatory

6 Live Demo

7  References are most used with functions  Enable the function to change parameters  Remove overhead from "sending" parameters int SomeFunction(int &parameterByReference,...) { //... //...}

8  Reference parameters to edit values  The function accesses the variable, not its copy  Variable passed in call to function is affected void MakePositive(int &number) { if(number < 0) { //this affects the variable in the caller number = -number; }} int main() { int a = -5; MakePositive(a); //after this line, a is 5 }

9  References to avoid overhead  Normal parameters are copied  Copying large objects can take too much time  Especially when this happens often  Almost no good reason to copy parameters  Any operation done on a copy can be done on a reference – with the same effect (when reading)  Sending by reference doesn't copy the object, just its reference (which is fast)

10  Example of fast and slow way of sending parameters to a function  Note: this is valid for potentially large objects (a vector can have many elements). Sending primitive types (int, char…) by copy and by reference is almost the same in speed int GetSum(vector &nums) //fast – only reference is sent { int sum = 0 int size = nums.size(); for(int i=0; i<size; i++) { sum += nums[i]; } return sum; } int GetSum(vector nums) //overhead – elements copied { int sum = 0 int size = nums.size(); for(int i=0; i<size; i++) { sum += nums[i]; } return sum; }

11  Reference parameters can be a problem  OK to send reference instead of the whole data  But does the function read or edit the data?  You can't be sure, especially if you're using 3 rd party code  const references solve this problem

12  const references  Work the same way, but data can only be read  A normal reference can be assigned to a const one  A const reference cannot be assigned to a normal one  i.e. a function cannot make a writeable reference from a const one int GetSum(const vector &nums) { //this function can't edit nums int sum = 0 int size = nums.size(); for(int i=0; i<size; i++) { sum += nums[i]; } return sum; }

13 Live Demo

14 Representing data in bytes, Variable addresses, Stack and Dynamic Memory

15  Computers work on data, stored in variables  Variables a program has at a given time are in the Random Access Memory (RAM)  RAM is just an array of bytes (software POV)  Each byte in RAM has an address (e.g. 0x000013A1 )  Its index in the array, usually as a hex number  Information is described by address and value  of the byte(s) at that address

16  Early computing days  Programming was moving and editing bytes  From one address to another  No "abstract" operations such as +, -, *, /  The programmer writes everything from scratch  Today, low-level memory is handled through:  Data types  Predefined operations (often on hardware level)  E.g. assigning values is copying memory

17  Most data types occupy more than one byte  Occupied bytes are sequential  E.g. data for a 4-byte int starting at 0x000013A3, also occupies 0x000013A4, 0x000013A5 and 0x000013A6  Address of a variable  The address of its first byte  The program can access the next bytes  By knowing the size of the data type

18  Example of a 4-byte integer in memory at address 0x13A3, with a value of 624  in a Big-endian system  i.e. most-significant byte is leftmost address Address0x13A20x13A30x13A40x13A50x13A60x13A7 Data…00000000 0000001001110000… int x = 624; cout<<&x<<endl; //outputs 0x13A3 //(in the described case) //(in the described case) //&x reads as "the address of x " //not the same as reference variables, //returns address of the first byte of x

19  Pointer – special variable, associated with an address in memory  Holds the memory address of another variable  "Points" to another variable  Can point to any byte in memory  Special " null " ( 0 ) value – shows the pointer currently holds no variable's address  Two essential operations for using pointers  Referencing  Dereferencing

20  Referencing – getting a variable's address  Variable's address (as a number) is returned  from the variable's identifier  i.e. gets the value of a pointer to the variable Address0x13A20x13A30x13A40x13A50x13A60x13A7 Data…00000000 0000001001110000… int x = 624; Here, referencing x gives 0x13A3 (5027 decimal) Let p be a pointer to x Then, the value of p is 0x13A3 (5027 in decimal)

21  Dereferencing – getting value from an address  The variable (the memory data) is returned  from a pointer to that variable  i.e. accesses memory at the address, pointed by the pointer * Note: we need to know the data type to dereference Address0x13A20x13A30x13A40x13A50x13A60x13A7 Data…00000000 0000001001110000… p is a pointer to address 0x13A3 Let us dereference p as a 4-byte integer* x The data for x is in bytes 0x13A3 to 0x13A6 Then the value of x is 624

22  Pointers – the common way to access memory  Most programming languages use pointers  Some allow full access (like C and C++)  Some hide pointers objects (C#, JS)  Reference and Dereference operators respectively create and evaluate pointers  Usually pointers can be incremented/decremented  i.e. "moved" to neighboring addresses

23 The & and * operators, Pointer values and arithmetic, const pointers, Building pointers from addresses

24  C++ provides lots of functionality for working with pointers  Assigning pointers to variables and dereferencing  Pointer types – int, char, string, etc.  Basic memory pointers – a.k.a. void pointers  Assigning pointers to arbitrary memory addresses  Incrementing/Decrementing pointers  Casting pointers from one type to another

25  Declaring and assigning pointers  C++ pointers have types and are declared as normal variables  A * (asterisk) sign prefix of the variable name denotes a pointer  Typically, assigning values requires a variable's address – which is returned by the & operator int v = 5; int *vPtr; vPtr = &v; //get the address (pointer to) v cout<<vPtr<<endl; //prints hex address of v

26  Getting values from pointers  C++ pointers have types  Dereferencing accesses memory as  Dereferencing is done through the * (asterisk) operator, as a prefix to an existing pointer  This gives direct read/write access to the memory  Note: * is used for declaration and dereferencing int v = 5; int *vPtr = &v; //here, * means create a pointer (*vPtr)++; //here, * means access the pointed memory cout<<*vPtr<<endl; //prints 6

27 Live Demo

28  Arithmetic operations on pointers  "Move" a pointer to a neighboring memory cell  Addresses are just numbers  Moving from one address to the next means incrementing/decrementing the pointer  Allowed arithmetic operations on pointers  Addition  Subtraction  i.e. move a pointer 1, 2, 3, etc… positions

29  Pointer arithmetics work in different ways  For different pointer types  E.g. incrementing int* and char* usually works differently  Increment/Decrement depend on data type  More precisely, the size of the data type  Incrementing a pointer of type T by 1 means incrementing the address to which it points to by 1 multiplied by sizeof(T)  Decrementing is analogous

30  Example of pointer arithmetics  Suppose the current system uses 1 byte for char, 2 bytes for short and 4 bytes for int char *charPtr =...//memory address 0x13A0 short *shortPtr =...//memory address 0x14A0 int *intPtr =...//memory address 0x15A0 charPtr++;shortPtr++;intPtr++; cout<<charPtr<<", "<<shortPtr<<", "<<intPtr<<endl; //prints 0x13A1, 0x14A2, 0x15A4

31  Example explanation 0x13A00x13A10x13A20x13A30x13A4 0x14A00x14A10x14A20x14A30x14A4 0x15A00x15A10x15A20x15A30x15A4 charPtr is 0x13A0, sizeof(char) is 1, 0x13A0 + 1 = 0x13A1 shortPtr is 0x14A0, sizeof(short) is 2, 0x14A0 + 2 = 0x14A2 intPtr is 0x15A0, sizeof(int) is 4, 0x15A0 + 4 = 0x15A4 charPtr shortPtr intPtr 0x13A0 + sizeof(char) 0x14A0 + sizeof(short) 0x15A0 + sizeof(int)

32 Live Demo

33  A pointer can be incremented/decremented with any value (not just using ++ and -- )  The expression p = p + 3 is valid  Where p is a pointer  Same rule for increasing by a multiple of type size is enforced  E.g. if p is an int pointer to address 0x15A0  after the expression is evaluated p points 0x15AC  The same rules apply for subtraction

34  As with references,  values pointed by pointers can be marked const  Unlike references,  pointers can change to what they point  Two pointer characteristics that can be const  Meaning a total of 4 pointer variations

35  Non-constant pointer to non-constant variable  Pointed memory can be modified by pointer  Pointed address can be changed  This is the "normal" pointer, from previous examples int x = 5; int *xPtr = &x; xPtr++;xPtr--; (*xPtr) = 4; int *otherXPtr = xPtr; //all operations valid

36  Non-constant pointer to constant variable  Pointed memory cannot be modified by pointer  Pointed address can be changed int x = 5; const int *xPtr = &x; xPtr++;xPtr--; (*xPtr) = 4; //error: read-only memory int *otherXPtr = xPtr; //error: invalid conversion

37  Constant pointer to non-constant variable  Pointed memory can be modified by pointer  Pointed address cannot be changed int x = 5; int * const xPtr = &x; xPtr++; //error: read-only pointer xPtr--; //error: read-only pointer (*xPtr) = 4; int *otherXPtr = xPtr; cout<<x<<endl;

38  Constant pointer to constant variable  Pointed memory cannot be modified by pointer  Pointed address cannot be changed int x = 5; const int * const xPtr = &x; xPtr++; ///error: read-only pointer xPtr--; ///error: read-only pointer (*xPtr) = 4; ///error: read-only memory int *otherXPtr = xPtr; ///error: invalid conversion cout<<x<<endl;

39  Pointers are useful as function parameters  Non-const pointers to non-const variables  Passing data to the function for modification  Traversing and modifying memory (arrays)  Non-const pointers to const variables  Efficiently passing large data to a function  Protecting the data from modification  Much like const references, so most compilers implement const references this way

40  const pointers in general  Useful for storing specific memory locations  And using them directly, i.e. no casting  Especially when working with:  Hardware expecting input at a specific address (i.e. you use const pointer to non-const memory)  Hardware producing output at a specific address (i.e. you use const pointer to const memory)

41 Live Demo

42  Pointers are just numbers and have addresses  So you can have pointers to pointers  Each pointer "level" is called an indirection  E.g., a pointer to a pointer is a double indirection  At declaration, one * per each indirection char x = 'a'; char * xPtr = &x; char ** xPtrPtr = &xPtr; Address0x13A00x14A00x15A0 Value'a'0x13A00x14A0 x * xPtr ** xPtrPtr

43  Pointers to pointers have many applications  Multidimensional arrays, composite objects, …  Modifying pointer address by functions  i.e. modify where the pointer points, not the data void MovePtrToNextZero(int ** pointerAddress) { int value = **pointerAddress; int value = **pointerAddress; while(value != 0) while(value != 0) { (*pointerAddress)++; (*pointerAddress)++; value = **pointerAddress; value = **pointerAddress; } } //Note: an often better (not always applicable) approach //is to return a new pointer, not modify the parameter //is to return a new pointer, not modify the parameter

44 Live Demo

45  C++ allows creating pointers to specific memory addresses  E.g. you can make a pointer point to 0x13A0  Regardless of whether or not the program is allowed to access that memory  Accessing the memory could trigger an access violation (error code 0xC0000005 )  Avoid creating pointers in such a way  Very unsafe and error-prone  Necessary in some cases (low-level code)

46  Initialize pointer to specific memory address  Simply provide the address as a number  Hex is the convention, but not obligatory  And cast it to the desired pointer type  Some argue cast should be reinterpret_cast  reinterpret_cast forces cast (regardless of type)  Also sort of says "Here be dragons!" int *ptr = (int*)5024; int *otherPtr = reinterpret_cast (0x13A0); cout << (ptr==otherPtr) << endl; //prints 1 cout << ptr << endl; //prints 0x13A0

47  Void pointers are a special type of pointer  Not associated with a data type  Can point to any variable/byte of memory  Useful as a "universal pointer"  Cannot do pointer arithmetic  Cannot modify memory or be dereferenced  Void pointers are useful after casted int a = 5; char b = 'x'; void *p; p = &a; p = &b; cout << *((char*)p) << endl; //prints 'x'

48  Function pointers are special pointers  Similar restrictions as void pointers  Typically used to pass functions as parameters  Declaration and calling are similar to normal function declaration and calling  With brackets around function name  * before function name, inside the brackets #include #include... double (*squareRootPtr)(double) = sqrt; cout << (*squareRootPtr)(9) << endl; //prints 3

49 Live Demo

50 Main Differences, Advantages and Disadvantages

51  Pointers are generally more versatile  Exist before references (pure C)  A lot of functionality and various types  Low(est)-level memory access  Base for polymorphism in C++ OOP  Harder to read, require a lot of operators  Relatively unsafe and error prone

52  References are generally tidier and safer  High level – act as variables, not addresses  No special operators except at declaration  Easy to initialize, work with and read  Memory-safe, hard to access wrong memory  Cannot fully replace pointers  Useful only for sending parameters to functions

53  References can point to only 1 variable  Through their lifetime  References cannot be NULL  References must be initialized on declaration  The address of a reference cannot be obtained  The & operator returns the variable's address  i.e. can't have pointer to reference or reference to reference

54  Pointer arithmetics don't work on references  You can't make an array of references  It is a bad practice to return a reference  It's usually ok to return a pointer  References usually implemented as const pointers in compilers  Although the standard doesn't dictate this

55 Arrays in Memory, Pointers and the [] Operator, Substituting Arrays with Pointers

56  In memory, arrays are sequences of variables  Which are sequences of bytes  i.e. an array is not fragmented in memory  A series of bytes, with a length of number of items * item type size  E.g. on a system where sizeof(short) is 2, an array of 3 short s, occupies a block of 6 bytes 0x13A20x13A30x13A40x13A50x13A60x13A7shortshortshort

57  The address of an array  Is the same as the address of its first element  Arrays also keep other information like  Array size, dimension size, etc.  Arrays often "degenerate" into pointers  Most array operations can be done with pointers  Arrays can't change the memory they point to  Same as a const pointer

58  The most important array "operator" – []  Is actually a syntax shorthand  Translates to pointer arithmetic  Addition is commutative, even for pointers: arrPtr + 3 == 3 + arrPtr == arr[3] == 3[arr] (where int *arrPtr = arr) int arr[5] {1, 2, 3, 4, 5}; int * arrPtr = arr; //We could also do the //operations below with arr //operations below with arr //Тhe following lines print the same cout<<arr[3]<<" at "<<&arr[3]<<endl; cout<<3[arr]<<" at "<<&3[arr]<<endl; cout<<*(arrPtr + 3)<<" at "<<(arrPtr + 3)<<endl;

59  The operator [] can be used with any pointer  Does additive pointer arithmetic  Dereferences the result  i.e. adds number in brackets with the pointer  Return value – the dereferenced result pointer  A pointer can be used to  Traverse, assign and read array-like memory  Represent an array as a function parameter  Pointers essential in using dynamic memory

60 Live Demo

61 "Stack" and "Heap" Memory, Storage Durations – automatic and dynamic

62  Programs usually use 2 types of memory  Stack memory  Heap memory  Stack memory  Separate for each process/thread  Stores function-local data, addresses, etc.  Automatically freed when out of scope  Heap memory  Manual, dynamic alloc/dealloc, usually larger

63  C++ utilizes stack and heap memory through  Automatic storage – mapped to the stack  Dynamic storage – works on the heap  Some ways of dynamic storage on the stack exist (mostly non-standard)  Storage types define how memory is managed  When/where memory for variables is allocated  What defines memory deallocation

64  C++ automatic storage – typical variables  Variables local to functions  Function parameters  Basically all variable-related memory  Pointers too – the address number, not the data  C++ dynamic storage  Memory allocated with operator new (C++03)  C++11 also offers Smart Pointers Smart PointersSmart Pointers  Memory addresses are assigned to pointers

65  Notes on automatic storage  Should be used for small data  Size known compile-time  Short lived – out of scope means deleted  Faster than dynamic  Freed upon function end. Don't return reference  Ok to pass as a parameter by reference/pointer  Bad to return by reference/pointer  Returned pointer/reference will point to deallocated (freed) memory

66  Notes on dynamic storage  Useful when needed memory is not known compile-time  Always accessed through pointers  Very agile for passing around the entire program's scope & lifespan  Manual allocation and deallocation  E.g. the operators new and delete  Dynamic memory is shared, i.e. if you allocate all of it, other processes can't allocate

67 Initializing Automatic Variables, Allocating and Deallocating Dynamic Memory

68  Automatic storage  Variables you declare in functions  Including references and pointers as "numbers"  i.e. addresses, not pointed memory  Arrays with size in declaration  Compile-time known size arrays  auto keyword  Explicitly denote automatic storage until C++11  C++ 11 changes the meaning (old meaning wasn't really needed)

69 Live Demo

70  Dynamic storage – memory allocated manually  Through operators like new  Through functions like malloc  Through C++11 Smart Pointers  Deallocated manually  If not deallocated can lead to a "memory leak"  Memory is released by code, not automatically  Accessed through pointers

71  Using the new operator  Initialization of a single instance of a type  new as prefix, type constructor  Initialization of multiple instances of a type  i.e. array of objects of the type  new as prefix, typename, brackets with a number  Note: heapInt and heapArray are automatic, but the pointed memory is dynamic and will not be deallocated automatically int *heapInt = new int();//value 0 int *heapArray = new int[5];//array of 5 random ints

72  Using the delete operator  Frees up memory allocated with new  Freeing up a single instance of a type  delete followed by pointer to the memory  Freeing up multiple instances (arrays) of a type  delete, brackets, pointer to memory  Note: if you lose all the pointers to the memory (they go out of scope), you can't deallocate it (unless you know its address) delete heapInt; delete[] heapArr;

73 Live Demo

74  References are just aliases of variables  Can only represent one variable; can be const  Pointers provide low level memory access  Can point to any memory address/variable  Can represent contiguous memory as arrays  Can move through memory (arithmetic)  We saw dynamic and automatic memory  Dynamic memory implies new and delete  Local variables are automatic

75 форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране http://algoacademy.telerik.com


Download ppt "References vs. Pointers, Addresses, Pointer Arithmetic, Pointers & Arrays, Stack & Heap memory Learning & Development Team Telerik."

Similar presentations


Ads by Google