pointers n.
Skip this Video
Loading SlideShow in 5 Seconds..
Pointers PowerPoint Presentation


304 Vues Download Presentation
Télécharger la présentation


- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Pointers • Class #10 – Pointer Review, Dynamic Memory Allocation, Linked Lists

  2. int *x; • x is a pointer to an integer. • You can use the integer x points to in a C++ expression like this: y = *x + 17; *x = *x +1; “the int x points to”

  3. MEMORY Address 0 1 2 3 4 5 ... ... &foo • In C++ you can get the address of a variable with the “&” operator. int foo; foo = 123; x = &foo; foo 123 &foomeans “the address of foo”

  4. Assigning a value to a dereferenced pointer A pointer must have a value before you can dereference it (follow the pointer). int *x; *x=3; int foo; int *x; x = &foo; *x=3; ERROR!!! x doesn’t point to anything!!! this is fine x points to foo

  5. Pointers to anything x some int int *x; int **y; double *z; some *int y some int z some double

  6. Pointers and Arrays • An array name is basically a const pointer. • You can use the [] operator with a pointer: int *x; int a[10]; x = &a[2]; for (int i=0;i<3;i++) x[i]++; x is “the address of a[2] ” x[i] is the same as a[i+2]

  7. Pointer arithmetic • Integer math operations can be used with pointers. • If you increment a pointer, it will be increased by the size of whatever it points to. int *ptr = a; *(ptr+2) *(ptr+4) *ptr a[0] a[1] a[2] a[3] a[4] int a[5];

  8. printing an array array version void print_array(int a[], int len) { for (int i=0;i<len;i++) cout << "[" << i << "] = " << a[i] << endl; } pointer version void print_array(int *a, int len) { for (int i=0;i<len;i++) cout << "[" << i << "] = " << *a++ << endl; }

  9. Static Memory Allocation • Two words you’ll hear a lot when talking about programming are static and dynamic. The variables • int x; • float money; • Employee janitor; • These objects are of fixed, known size, and the compiler arranges the required space as it turns source code into a binary or executable program. • Statically allocated objects are put into a memory space known as the stack. • The key point is that for these objects their size is fixed at compile time.

  10. Dynamic Memory Allocation • Now, suppose we don't know the size of an object until program execution. • Examples of this are a buffer to hold a block of text of variable size, or an array with an undetermined number of elements • We could try to size the buffer or array to be large enough to hold the worst case, that is, to be big enough to hold anything we should encounter.

  11. Dynamic Memory Allocation • But, there are two problems with this strategy. • First, it consumes memory unnecessarily. This is less of an issue than in the past when memory was more limited, but still impacts overall system performance. • Second, no matter how much memory is statically set aside for our object, we can never be sure it will be large enough. This is really a ticking time bomb. Eventually, someone will try to load one too many elements, or type on too many words and then our program will either crash or run erratically.

  12. Allocating Single Objects • During program execution dynamically allocated memory comes form a pool of memory known as the heap or free store. • It allocated using the C++ operator "new" and freed using the operator "delete". To see how this works let's dynamically allocate some objects of intrinsic data types.

  13. Allocating Single Objects • int *IDpt = new int;float *theMoney = new float;char *letter = new char; • The "new" operator returns the address to the start of the allocated block of memory. • This address must be stored in a pointer. • New allocates a block of space of the appropriate size in the heap for the object. • For instance, "new int" reserves four bytes (on most operating systems), while "new char" reserves a single byte.

  14. Allocating Single Objects • Objects dynamically allocated using the previous syntax are uninitialized. They contain whatever random bits happen to be at their memory location. Before use, a value must be *IDpt = new int;*IDpt = 5; • Alternatively, C++ provides a syntax which initializes the allocated object via the "new" *IDpt = new int(5);//Allocates an int object and initializes it to value 5.char *letter = new char('J');

  15. Dynamically Allocating Arrays • So far, we’ve been using statically allocated arrays. This is why you had to (or were supposed to) use a constant when you created your Array. • Arrays may also be dynamically allocated. • int a = 1024;int *pt = new int[a];//allocates an array of 1024 intsint *myBills = new double[10000]; • Also, note the difference between:int *pt = new int[1024];//allocates an array of 1024 intsint *pt = new int(1024);//allocates a single int with value 1024

  16. Dynamically Allocating Structs • So we’ve now created basic types (ints, chars) and Arrays on the heap, using the new operator. • We can also create Structs in the same way. Struct Date { int month; int year; int day; }; Date *bdayPtr = new Date(); • This creates an UNINITIALIZED Date struct on the heap, and returns a Pointer to it.

  17. Dynamically Allocating Structs • To initialize our Date Object Date *bdayPtr = new Date(); • We can use code like *bdayPtr.month = 5; * = 14; *bdayPtr.year = 1980;

  18. The -> operator • The combination of the dereference ( * ) and the dot operator (.) was very common, so C++ has a shortcut for that, the -> operator. bdayPtr -> month = 5; bdayPtr -> day = 14; bdayPtr -> year = 1980; is exactly the same as *bdayPtr.month = 5; * = 14; *bdayPtr.year = 1980;

  19. Linked Lists • So far we’ve only seen 1 “list” type structure, an array, which we know is a contiguous block of memory addresses accessed via a pointer. • Arrays suffer from a lot of problems, namely, they can’t be resized, and adding something in the middle makes you move all the elements in the array to “Make Room”. • Linked Lists avoid this limitation but not being contiguous in memory.

  20. Linked Lists • So, with an array, if we know the location of the ith element, how do we know the location of the I+1th element? • Sure.. mem location i + sizeof(data type of I) • Basically, since we know it’s right after i, we can just move a certain number of calls over in memory, nothing else is required. • With Linked Lists, we don’t have this luxury. So, each item in a Linked List must contain a Pointer to the next element of the list.

  21. The Date struct • So, back to our Date struct. Struct Date { int month; int year; int day; }; • Now we have to make it have a Pointer to the next element in the array. • What type of Pointer are we going to need to point to our next Object? What is the Data type of the next Object? • So, we can redefine our Date struct as…

  22. The Date struct Struct Date { int month; int year; int day; Date* next }; • We add a Date Pointer, which will Point to the next element in the list.

  23. head Start and stop of list • So, now let’s look at a linked list visually • Notice two things absent from previous discussion, something to mark the start of the list, and something to mark the end. • To mark the end is easy.. set the Next Pointer to null. • To mark the start, we use a Date* Pointer, usually named head, or headPtr;

  24. Linked List • To summarize so far • A linked list is a list of nodes in which each node has a member variable that is a pointer that points to the next node in the list • The first node is called the head • The pointer variablehead, points to the first node • The pointer named head is not the head of the list…it points to the head of the list • The last node contains a pointer set to NULL

  25. Ok, let’s start making one • To create the first node, the operator new is used to create a new dynamic variable:head = new Node; • Now head points to the first, and only, node in the list

  26. head Keep going.. • Now that head points to a node, we need to give values to the member variables of the node: head->data = 3; head->next = NULL; • Since this node is the last node, the link is set to NULL

  27. nextNode head Now, let’s attach 1 node • First, we need to create it, and set values in it. Node nextNode=new Node; nextNode->data = 5; nextNode->next = NULL; • So now we have

  28. nextNode nextNode head head So, to connect them • Before head->next = nextNode; • Note, nextNode is pointing at element 2 of the list, but it really isn’t needed anymore. We can reuse this pointer variable to create new nodes by reallocating it with new.