Download presentation
Presentation is loading. Please wait.
Published byConrad Hill Modified over 8 years ago
1
Pointers in C++
2
7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of a memory cell initially undefined a "pointer to int" declaration int * p; // pointer variable p itself is static here Typically, pointer variables are used to store memory address of dynamically allocated objects (e.g. int for p to point at) p = new int;
3
7a-3 Pointers To help keep things straight, it’s useful to pretend there are parentheses in the pointer declarations: (int *) p; means that p is of type int* (i.e.: that is, p is a pointer to an int location) Don’t actually write declarations this way
4
7a-4 Dereferencing Operator The expression *p denotes the memory cell to which p points Here, * is called the dereferencing operator Be careful not to dereference a pointer that has not yet been initialized: int * p; p ? *p = 7; Address in p could be any memory location Attempt to put a value into an unknown memory location will result in a run-time error, or worse, a logic error
5
7a-5 The Null Pointer The null pointer is a special constant which is used to explicitly indicate that a pointer does not point anywhere NULL is defined in the standard library (or ) In diagrams, indicated as one of: NULL.
6
7a-6 The Address Operator The expression &x denotes the address of a variable x Here, & is called the address operator int x, *p; p ? x ? p = &x; *p = 4; p x ? p x 4 Value of x has been changed by *p = 4;
7
7a-7 Pointer Example int *p, *q, x; p = &x; *p = 4; p x (or *p) q 4 ? p = new int; p x q 4 ? Call stackHeap ? *p
8
7a-8 Pointer Example (cont’d) *p = 8; p x q 4 ? 8 q = p; Call stackHeap p x q 4 8 *p *p or *q
9
7a-9 Pointer Example (cont’d) q = new int; *q = 5; Call stackHeap p x q 4 8 *p 5 *q
10
7a-10 Pointer Example (cont’d) p = NULL; Call stackHeap p x q 4 8 5 *q. This location is no longer has a name, is no longer reachable from the program, and cannot be deallocated: we have a memory leak
11
7a-11 Pointer Example (cont’d) delete q; q = NULL; Call stackHeap p x q 4 8 5. Allocated but unreachable. Deallocated, and available for reuse
12
7a-12 Dynamic Allocation of Arrays Use the new operator to allocate an array dynamically An array name is really a pointer to the array’s first element double* arr; arr = new double[5]; Call stackHeap arr ? ? ? ? ?
13
7a-13 Arrays of Pointers It’s possible to have arrays of pointers The array name is a pointer to an array of pointers: int** arrayOfPtr; int j = 6; k = 4; arrayOfPtr = new int*[4]; jk 64 arrayOfPtr ???? 0123 Allocated in heap space; pointers in array are not initialized yet
14
7a-14 Arrays of Pointers arrayOfPtr[0] = &k; arrayOfPtr[2]=&j; arrayOfPtr[3] = new int; j k 6 4 arrayOfPtr Call stackHeap ? 0123 ?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.