Dynamic Data
- You should read chapter 14.
- Up until now all of our storage has been allocated at compile time.
- Declared variables
- Declared arrays
- This is called static data.
- Don't confuse this with the static reserved word.
- This marks a variable to have a lifetime that extends beyond the invocation of the routine in which it is declared.
- In general memory is organized
- The runtime stack or stack.
- This is where subroutines allocate memory for parameters and local variables.
- The heap
- This is where dynamic memory comes from.
- We can allocate memory from the heap at run time
-
- When we allocate memory from the heap, we need a place to store it.
- Read section 10.7, Pointers.
- Pointers are an ADT
- Domain: A location or the special value NULL
- Operations:
- assign the pointer the value of a location
- access the data at the location to which the pointer is pointing.
- In most languages, pointers are implemented as memory addresses.
- In C/C++ we declare a pointer to a specific type of data.
- int a declares an integer sized chunk of static memory (on the stack, or data/bss segments).
- This memory is called a.
- This memory can store an integer.
- a = 7 places the value 7 into a.
- int * ptr declares a integer pointer sized chunk of memory (on the stack, or data/bss segments).
- this memory can store an integer pointer.
- ptr = NULL
- ptr = &a;
- You could, but never would do this (Except for example programs)
- *ptr dereferences or access the memory pointed to by the pointer.
- cout << *ptr << endl; will print the value (7) that ptr points to.
- *ptr = 22 assigns 22 to the memory ptr points to.
- Declaring pointers
- The * is associated with the variable in the declaration
- int *ptr1, ptr2
- Does not do what you think
- ptr1 is declared to be an integer pointer.
- ptr2 is just an integer.
- int *ptr1, *ptr2 is the proper way to do this.
- Pointers and arrays
- Arrays are pointers, that is why they are so weird.
- int a[10];
- int * b
- b = a sort of does what you think it does.
- Pointers to structures.
- If DataT is a class with member data member1 and member2
- DataT * ptr, data declares an instance and a pointer to a DataT.
- ptr = &data will point ptr at data.
- ptr->member1 = someValue assigns someValue to member1
- cout << ptr->member2 will print out member2
- Pointers to classes.
- If ClassT is a class, with member functions One(int i) and Two().
- ClassT * ptr, data declares a pointer to a ClassT and an instance of the ClassT.
- ptr = &data; points ptr at data.
- ptr->One(7) calls the One member function.
- cout << ptr->Two() calls the Two member function.
- So there are three basic operations
- * dereferences a pointer to an item.
- -> dereferences a poitner to a member of a structure
- [] dereference a pointer to an item in an array
- & return a pointer to a instance of a variable (or other things)