Download presentation
Presentation is loading. Please wait.
2
Pointers and Dynamic Variables
3
Objectives on completion of this topic, students should be able to:
Correctly allocate data dynamically * Use the new operator * Save an address in a pointer * Understand where dynamically allocated data is stored Know how and when to delete dynamically allocated data Understand how a Vector works.
4
Dynamic Memory Allocation
Review: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5; . . . } int main ( ) this is a global variable it is stored in the data segment. this is a local variable it is stored on the stack.
5
Dynamic Memory Allocation
Review: Consider the following code: int valueOne = 10; int someFunction( ) { int valueTwo = 5; . . . } int main ( ) valueOne exists for the entire life of the program. valueTwo comes into existence when it is declared, and disappears when the function ends.
6
What if you want to control when a variable
comes into existence, and when it goes away?
7
The new operator int* a = new int;
This is a pointer. This variable is stored on the heap. Storage from the heap is allocated dynamically as your program executes, int* a = new int; CoinBank* myBank = new CoinBank(5,3); These variables come into existence when they are declared. They don’t have names, but are accessed through pointers. They exist and take up memory until explicitly deleted.
8
Some languages, like Java and C# have a
garbage collector to clean up data on the heap that is no longer in use. C++ does not – you have to do it!
9
delete Dynamically allocated variables will stay around until you explicitly delete them. Thus, they are completely under programmer control. To delete a dynamically allocated variable you would write delete a; where a is a pointer to the variable. When dynamically allocated variables are not properly deleted, your program will have a “memory leak”, which is really bad.
10
Dynamic Arrays Recall that when we talked about arrays, we noted that the array size given in the array declaration had to be a constant value. That is, the array size had to be fixed at compile time. This presents some difficulties: * either we guess too low and the array is not big enough to hold all of the data required, or * we guess to high and we waste space because elements of the array are not used.
11
One approach to solving this problem is to allocate
the storage required for the array at run-time. int size; cout << “How big is the array?”; cin >> size; int *myArray; myArray = new int [size]; since we are allocating storage at run-time, we are allowed to use a variable as the array size.
12
Now, remembering the relationship between an array name
and a pointer, we can use the dynamic array just like a normal array… myArray [5] = 15; cout << myArray[n]; Remember, myArray is just the name of the pointer where we saved the address returned by the new operator.
13
delete [ ] Whenever you use [ ] with new to allocate an array dynamically, you must use the corresponding form of the delete, delete [ ]. That is, if you write int *myArray; myArray = new int [10]; You must write delete [ ] myArray; to delete the array!
14
If you do not delete dynamically allocated
data when you are done with it, your program may crash and it has the potential to crash your computer.
15
The -> Operator When we dynamically allocate storage for an
object, we no longer use the dot operator to access its data members. Instead we use the -> operator. piggyBankPtr = new PiggyBank; piggyBankPtr->moneyInBank = 12.45;
16
Pointers and Dynamic Arrays
Chapter 9 Pointers and Dynamic Arrays
17
Overview 9.1 Pointers Pointer Arithmetic 9.2 Dynamic Arrays
18
Objectives on completion of this topic, students should be able to:
Correctly use pointers in a C++ program * Take the address of a variable * Dereference a pointer * Do pointer arithmetic Explain the relationship between an array and a pointer * Use pointers to access array elements
19
9.1 Pointers
20
Pointers Assume that we have declared an integer variable
v1, and that the compiler has assigned the memory location for that integer value. 000032 v1 is the name of the variable. We can access the variable by simply using its name. v1 = 34; if integer variables take up 4 bytes of memory on this computer, then the address of the first byte of the integer is
21
Pointers The address of the variable is 000032.
We can store the address of a variable in a special data type called a pointer.
22
Pointers A pointer is the memory address of a variable
Memory addresses can be used as names for variables If a variable is stored in three memory locations, the address of the first can be used as a name for the variable. When a variable is used as a call-by-reference argument, its address is passed
23
Pointers Tell Where To Find A Variable
An address used to tell where a variable is stored in memory is a pointer Pointers "point" to a variable by telling where the variable is located
24
Declaring Pointers Pointer variables must be declared to have a pointer type Example: To declare a pointer variable p that can "point" to a variable of type double: double *p; The asterisk identifies p as a pointer variable
25
Multiple Pointer Declarations
To declare multiple pointers in a statement, use the asterisk before each pointer variable Example: int *p1, *p2, v1, v2; p1 and p2 point to variables of type int v1 and v2 are variables of type int
26
The address of Operator
The & operator can be used to determine the address of a variable which can be assigned to a pointer variable Example: p1 = &v1; p1 is now a pointer to v v1 can be called v1 or "the variable pointed to by p1"
27
Declaring Pointers int v1; int *v1Ptr; v1Ptr = &v1;
this statement declares the integer variable v1. Let us assume that the address of v1 in memory is int v1; int *v1Ptr; v1Ptr = &v1; this statement declares v1Ptr to be a variable of type integer pointer. That is, v1Ptr can contain a pointer to (the address of) an integer. Note that pointers are typed. This pointer points to an integer. this statement stores the address of the variable v1 in the variable v1Ptr. The & is called the address-of operator. To declare a pointer variable, place an asterisk in front of the variable name.
28
Declaring Pointers 0 0 0 0 3 2 v1Ptr is said to point to v1. v1 000032
000036 v1Ptr v1Ptr is said to point to v1.
29
Be careful when declaring pointers!
int *aptr, bptr; but bptr is an int! aptr is a pointer
30
you must declare them this way!
int *aptr, *bptr;
31
The Dereferencing Operator
000032 4 5 v1 000036 v1Ptr
32
The Dereferencing Operator
C++ uses the * operator in yet another way with pointers The phrase "The variable pointed to by p" is translated into C++ as *p Here the * is the dereferencing operator p is said to be dereferenced
33
The Dereferencing Operator
int v1; int *v1Ptr; v1Ptr = &v1; *v1Ptr = 45; cout << v1; the asterisk used as shown here is called the de-referencing operator. This statement says store the value 45 in the variable pointed to by v1Ptr.
34
Null Pointers There is a special value “nullptr” that is used to
indicate that a pointer does not point to anything. When first declaring a pointer, it is a good idea to set its value to nullptr, like this: int* intPtr = nullptr; You cannot dereference a null pointer. You should always test a pointer before you use it, to make sure it is not a NULL pointer: if (intPtr != nullptr) . . .
35
v1 and *p1 now refer to the same variable
A Pointer Example v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << endl; cout << *p1 << endl; output: v1 and *p1 now refer to the same variable
36
Pointer Assignment The assignment operator = is used to assign the value of one pointer to another Example: If p1 still points to v1 (previous slide) then p2 = p1; causes *p2, *p1, and v1 all to name the same variable
37
Pointer Assignment int v1, v2; int *v1Ptr, *v2Ptr; v1Ptr = &v1;
000032 000036 45 int v1, v2; int *v1Ptr, *v2Ptr; v1Ptr = &v1; *v1Ptr = 45; v2Ptr = v1Ptr; *v2Ptr = *v1Ptr; v1Ptr v2Ptr 000040 000044 000032 000032
38
Caution! Pointer Assignments
Some care is required making assignments to pointer variables p1= p3; // changes the location that p1 "points" to *p1 = *p3; // changes the value at the location that // p1 "points" to Display 9.1
39
void Pointer Recall that pointers are typed. int x = 3; int *xPtr;
float *yPtr; xPtr = &x; yPtr = xPtr; this assignment won’t work because the pointer types are not the same!
40
void Pointer The void pointer is a generic pointer type. That is, it can hold the address of any data type. So, we could use a void pointer to write int x = 3; int *xPtr; void *yPtr; xPtr = &x; yPtr = xPtr; Now this statement will compile and execute with no errors because yPtr is a generic pointer.
41
void Pointer int x = 3; int *xPtr; void *yPtr; xPtr = &x; yPtr = xPtr;
cout << *yPtr; However, this statement will not work. Because a void pointer is generic, it does not keep track of what kind of data it points to. Therefore, the computer cannot do the conversion necessary to print out the data pointed to by the void pointer.
42
Casting int x = 3; int *xPtr; void *yPtr; xPtr = &x; yPtr = xPtr;
cout << *(static_cast<int*>(yPtr) ); If we know what the data type is that the pointer points to, we can cast the pointer to the correct type to make the statement work. The type we are casting to, in this case an int* appears in parenthesis in front of the variable name.
43
Common Pointer Problems
Common Pointer Errors Trying to dereference a NULL or uninitialized pointer Confusing pointers with the data to which they point Returning a pointer to data declared locally in a function
44
Pointers and Arrays int myArray [4]; * myArray is an integer pointer.
The name of an array is really a const pointer to the first element in the array! myArray int myArray [4]; * myArray is an integer pointer. * myArray is a const pointer ( so that the address of myArray is not accidentally lost!) * myArray can be assigned to a pointer variable.
45
Array/Pointer Duality Law
Pointers and Arrays Array/Pointer Duality Law a[n] is identical to *(a + n) where a is a pointer to an array and n is an integer offset.
46
Pointers and Arrays #include <iostream> using namespace std;
int main ( ) { int intArray[ ] = {1, 3, 5, 7, 9}; cout << "\nintArray = " << intArray; cout << endl; return 0; } what will this statement display?
47
Pointers and Arrays #include <iostream> using namespace std;
int main ( ) { int intArray[ ] = {1, 3, 5, 7, 9}; cout << "\nintArray = " << intArray; cout << “\n*intArray = “ << *intArray; cout << endl; return 0; } what will this statement display?
48
Pointer arithmetic Pointer Arithmetic
Since a pointer is just a normal variable we can do arithmetic on it like we can for any other variable. For example int *myPtr; myPtr++; // increment the pointer myPtr--; // decrement the pointer myPtr += 4; // add four to myPtr
49
Pointers and Arrays Note however, that in C++, pointer arithmetic
is only meaningful within an array. address int x[2]; int *aPtr; aPtr = x; *aPtr = 5; aPtr++; *aPtr = 8; X[0] 000016 5 X[1] 8 000020 aPtr 000024 000016 000020 Note: When we increment a pointer, we increment it by the size of the data type it points to!
50
Note the following interesting use of pointers and arrays.
int myArray [4]; int* arrayPtr; arrayPtr = myArray; myArray [3] = 125; *(arrayPtr + 3) = 125; *(myArray + 3) = 125; arrayPtr [3] = 125; the assignment works because myArray is an int pointer. use pointer arithmetic to move the pointer to the 4th element in the array (3 times size of int) these are all equivalent. aha … you can also use pointer arithmetic on the array name. and index notation on the pointer.
51
The -> Operator We normally use the dot operator to reference member data or Member functions in an object. For example myCircle.getArea( ); But if we have a pointer to the object we have to use the -> operator, like this myCirclePtr->getArea( );
52
The pointer “this” Every object contains a data member named this,
that contains the address of the object itself.
53
The pointer ‘this’ So, in the function myCircle.getArea( );
You could write double Circle::getArea( ) { return this->radius * this->radius * PI; } i.e. this->radius refers to the radius data member in the object receiving the getArea message.
54
Dynamic variables
55
The new Operator Using pointers, variables can be manipulated even if there is no identifier for them To create a pointer to a new "nameless" variable of type int: p1 = new int; The new variable is referred to as *p1 *p1 can be used anyplace an integer variable can cin >> *p1; *p1 = *p1 + 7;
56
Dynamic Variables Variables created using the new operator are called dynamic variables Dynamic variables are created and destroyed while the program is running Additional examples of pointers and dynamic variables are shown in An illustration of the code in Display 9.2 is seen in Display 9.2 Display 9.3
57
new and Class Types Using operator new with class types calls a constructor as well as allocating memory If MyType is a class type, then MyType *myPtr; // creates a pointer to a // variable of type MyType myPtr = new MyType; // calls the default constructor myPtr = new MyType (32.0, 17); // calls Mytype(double, int);
58
Basic Memory Management
An area of memory called the freestore or the heap is reserved for dynamic variables New dynamic variables use memory in the freestore If all of the freestore is used, calls to new will fail Unneeded memory can be recycled When variables are no longer needed, they can be deleted and the memory they used is returned to the freestore
59
The delete Operator When dynamic variables are no longer needed, delete them to return memory to the freestore Example: delete p; The value of p is now undefined and the memory used by the variable that p pointed to is back in the freestore
60
Dangling Pointers Using delete on a pointer variable destroys the dynamic variable pointed to If another pointer variable was pointing to the dynamic variable, that variable is also undefined Undefined pointer variables are called dangling pointers Dereferencing a dangling pointer (*p) is usually disasterous
61
9.2 Dynamic Arrays
62
Dynamic Arrays A dynamic array is an array whose size is determined when the program is running, not when you write the program
63
Pointer Variables and Array Variables
Array variables are actually pointer variables that point to the first indexed variable Example: int a[10]; typedef int* IntPtr; IntPtr p; Variables a and p are the same kind of variable Since a is a pointer variable that points to a[0], p = a; causes p to point to the same location as a
64
Pointer Variables As Array Variables
Continuing the previous example: Pointer variable p can be used as if it were an array variable Example: p[0], p[1], …p[9] are all legal ways to use p Variable a can be used as a pointer variable except the pointer value in a cannot be changed This is not legal: IntPtr p2; … // p2 is assigned a value a = p2 // attempt to change a Display 9.4 Display 9.5
65
Creating Dynamic Arrays
Normal arrays require that the programmer determine the size of the array when the program is written What if the programmer estimates too large? Memory is wasted What if the programmer estimates too small? The program may not work in some situations Dynamic arrays can be created with just the right size while the program is running
66
Creating Dynamic Arrays
Dynamic arrays are created using the new operator Example: To create an array of 10 elements of type double: typedef double* DoublePtr; DoublePtr d; d = new double[10]; d can now be used as if it were an ordinary array! This could be an integer variable!
67
Dynamic Arrays (cont.) Pointer variable d is a pointer to d[0]
When finished with the array, it should be deleted to return memory to the freestore Example: delete [ ] d; The brackets tell C++ a dynamic array is being deleted so it must check the size to know how many indexed variables to remove Forgetting the brackets, is not legal, but would tell the computer to remove only one variable Display 9.6 (1) Display 9.6 (2)
68
Pointer Arithmetic (Optional)
Arithmetic can be performed on the addresses contained in pointers Using the dynamic array of doubles, d, declared previously, recall that d points to d[0] The expression d+1 evaluates to the address of d[1] and d+2 evaluates to the address of d[2] Notice that adding one adds enough bytes for one variable of the type stored in the array
69
Pointer Arthmetic Operations
You can add and subtract with pointers The ++ and - - operators can be used Two pointers of the same type can be subtracted to obtain the number of indexed variables between The pointers should be in the same array! This code shows one way to use pointer arithmetic: for (int i = 0; i < array_size; i++) cout << *(d + i) << " " ; // same as cout << d[i] << " " ;
70
Multidimensional Dynamic Arrays
To create a 3x4 multidimensional dynamic array View multidimensional arrays as arrays of arrays First create a one-dimensional dynamic array Start with a new definition: typedef int* IntArrayPtr; Now create a dynamic array of pointers named m: IntArrayPtr *m = new IntArrayPtr[3]; For each pointer in m, create a dynamic array of int's for (int i = 0; i<3; i++) m[i] = new int[4];
71
A Multidimensial Dynamic Array
The dynamic array created on the previous slide could be visualized like this: IntArrayPtr's m IntArrayPtr * int's
72
Deleting Multidimensional Arrays
To delete a multidimensional dynamic array Each call to new that created an array must have a corresponding call to delete[ ] Example: To delete the dynamic array created on a previous slide: for ( i = 0; i < 3; i++) delete [ ] m[i]; //delete the arrays of 4 int's delete [ ] m; // delete the array of IntArrayPtr's Display 9.7 (1) Display 9.7 (2)
73
Section 9.2 Conclusion Can you
Write a definition for pointer variables that will be used to point to dynamic arrays? The array elements are of type char. Call the type CharArray. Write code to fill array "entry" with 10 numbers typed at the keyboard? int * entry; entry = new int[10];
74
Chapter 9 -- End
75
Display 9.1 Back Next
76
Display 9.2 Back Next
77
Display 9.3 Back Next
78
Display 9.4 Back Next
79
Display 9.5 Back Next
80
Display 9.6 (1/2) Back Next
81
Display 9.6 (2/2) Back Next
82
Display 9.7 (1/2) Back Next
83
Display 9.7 (2/2) Back Next
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.