12: Pointers and Dynamic Arrays

What We Will Cover


Continuations

Questions from last class?

12.1: Pointers

Objectives

At the end of the lesson the student will be able to:

  • Declare pointers and initialize pointer variables
  • Code basic pointer operations
  • Describe dynamic memory management

12.1.1: Pointer Variables

  • Pointer variables (pointers) store memory addresses rather than actual values
  • Pointers "point" to a variable by telling where the variable is located
  • Recall that memory addresses are numbered locations
  • Pointer variables store the value of a memory location
  • You have used pointers already!
    • Call-by-reference parameters
    • Address of actual argument was passed
  • Using pointers, you can control low-level memory operations of a computer
  • This control can increase the capabilities of the C++ programs you write

Declaring Pointers

  • Pointer variables must be declared to have a pointer type
  • For example, to declare a pointer variable named ptr:
  • double *ptr;
  • The asterisk identifies the variable ptr as a pointer
  • You can declare multiple pointers in a statement:
  • int *p1, *p2, v1, v2;
  • p1 and p2 point to variables of type int
  • v1 and v2 are variables of type int

12.1.2: Assigning Values to Pointers

  • You can use the "address of" operator (&) to assign addresses to pointers
  • For example:
  • p1 = &v1;
  • p1 is now a pointer to v1
  • v1 can be called v1 or "the variable pointed to by p1"

12.1.3: 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 known as dereferencing operator
    • p is said to be dereferenced
  • For example:
  • v1 = 0;
    p1 = &v1; // v1 and *p1 now refer to the same variable
    *p1 = 42; // dereferencing operator gets the value
    cout << v1 << endl;
    cout << *p1 << endl;
    

12.1.4: Using the Assignment Operator

  • You can use the assignment operator = to assign the value of one pointer to another
  • For example, if p1 still points to v1:
  • p2 = p1;
  • Now *p2, *p1, and v1 all refer to the same variable
  • Be careful when making assignments to pointer variables:
  • p1= p3;    // changes the location to which p1 "points"
    *p1 = *p3; // changes the value at the location to which
               // p1 "points"
    
  • Pointer Assignment

12.1.5: Dynamic Memory Management

  • Using pointers, variables can be manipulated even without an identifier for them
  • For example, to create a pointer to a new "nameless" variable of type int:
  • p1 = new int;
  • The new variable is referred to as *p1
  • You can use *p1 anyplace you can use an integer variable
  • cin >> *p1;
    *p1 = *p1 + 7;
    
  • Variables created using the new operator are called dynamic variables
  • Dynamic variables are created and destroyed while the program is running
  • Dynamically creating and destroying variables is called dynamic memory management

For example:

//Program to demonstrate pointers and dynamic variables
#include <iostream>
using namespace std;

int main(void) {
    int *p1, *p2;

    p1 = new int;
    *p1 = 42;
    p2 = p1;
    cout << "*p1 == " << *p1 << endl;
    cout << "*p2 == " << *p2 << endl;

    *p2 = 53;
    cout << "*p1 == " << *p1 << endl;
    cout << "*p2 == " << *p2 << endl;

    p1 = new int;
    *p1 = 88;
    cout << "*p1 == " << *p1 << endl;
    cout << "*p2 == " << *p2 << endl;

    cout << "Hope you got the point of this example!\n";
    return 0;
}
  • 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);
    
  • C++ programs reserve an area of memory called the freestore or heap
  • New dynamic variables use memory in the freestore
  • If all of the freestore is used, calls to new will fail
  • You can delete and recycle memory that is no longer needed
  • Use the delete operator to return memory to the freestore
  • For example:
  • delete ptr;
  • Memory used by the variable that ptr pointed to is released to the freestore
  • The value of ptr is now undefined
  • 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 (*ptr) is usually disastrous

12.1.6: Summary

  • Pointer variables (pointers) store memory addresses rather than actual values
  • A memory address tells where a variable is stored
  • Pointers "point" to a variable by telling where the variable is located
  • Using pointers, you can control low-level memory operations of a computer
  • To declare a pointer, use an asterisk operator
  • double *ptr;
  • You can use the "address of" operator (&) to assign addresses to pointers
  • p1 = &v1;
  • You can also use the asterisk operator to dereference pointers
  • *p1 = 42;
  • You can use the assignment operator = to assign the value of one pointer to another
  • p2 = p1;
  • Which should not be confused with:
  • *p1 = *p3;
  • You can create dynamic variables using the new operator
  • p1 = new int;
  • To destroy dynamic variables, use the delete operator
  • delete p1;

Exercise 12.1

With a partner, if needed, take 5 minutes to complete the following:

  1. Start a text file named exercise12.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 12.1
  4. Submit all exercises for today's lesson in one file unless instructed otherwise
  5. Complete the following and record the answers to the questions in exercise12.txt.

Specifications

  1. Write a declaration for a variable called numberPtr that will point to integer values.
  2. Write a declaration for a variable called charPtr that will point to char values.
  3. Give an example of at least three uses of the * operator. Add a comment that names each use.

12.2: Dynamic Arrays

Objectives

At the end of the lesson the student will be able to:

  • Describe the similarities between array variables and pointers
  • Use dynamic arrays in programs

12.2.1: Arrays and Pointers

  • Array variables are really pointer variables
  • Recall that array elements are stored sequentially in memory addresses
  • Array variable ‘refers to’ the first indexed variable
  • Thus an array variable is a kind of pointer variable

For Example

    int a[10];
    int *p;
    
  • Both a and p are pointer variables
  • You can assign a to p
  • p = a;
    
  • Variable p now points where a points
  • Now you can use array brackets with pointer variable p
  • p[0] = 10;
    
  • Note that variable a cannot be changed because it is a constant variable
  • a = p;  // ILLEGAL!
    

12.2.2: Creating and Deleting Dynamic Arrays

  • Arrays are limited because you must set the size before you run your program
  • You do not always know the size your program will need
  • Best you can do is estimate the maximum size
  • Dynamic arrays use pointers to get around this limitation

Creating Dynamic Arrays

  • To create a dynamic array, you use the new operator
  • int *p = new int[10];
    
  • Creates a dynamically allocated array of 10 elements with a base type of int

Deleting Dynamic Arrays

  • Since a dynamic array is allocated dynamically at run-time, you should destroy it at run time
  • delete [] p;
    
  • De-allocates all memory for dynamic array
  • Use brackets to Brackets indicate you are deallocating an array type
  • Since p still points to the location in memory, you should set p = NULL
  • p = NULL;
    

12.2.3: Using Dynamic Arrays with Functions

  • Recall that array type are NOT allowed as the return-type of function
  • int [] someFunction(); // ILLEGAL!
    
  • However, you can return a pointer from a function
  • Thus, you can return a pointer to an array base type
  • int* someFunction();   // LEGAL!
    

For Example

#include <iostream>
using namespace std;

int* makeArray(int length, int value);
void showArray(int values[], int length);

int main(void) {
    int arraySize, arrayValue;
    cout << "How large of an array do you want? ";
    cin >> arraySize;
    cout << "What value for each element? ";
    cin >> arrayValue;

    int* p = makeArray(arraySize, arrayValue);
    showArray(p, arraySize);
    delete [] p;

    return 0;
}

int* makeArray(int length, int value) {
    int* array = new int[length];
    for (int i = 0; i < length; i++) {
        array[i] = value;
    }
    return array;
}

void showArray(int values[], int length) {
    for (int i = 0; i < length; i++) {
        cout << values[i] << " ";
    }
    cout << endl;
}

12.2.4: Summary

  • A dynamically allocated array has its size determined when the program is running
  • Dynamic arrays are implemented as a dynamic variable of an array type
  • int *p = new int[10];
    
  • Since a dynamic array is allocated dynamically at run-time, you should destroy it at run time as well
  • delete [] p;
    
  • You can return a pointer to an array base type from a function
  • int* someFunction();

Exercise 12.2

  1. Write a program that creates an integer array dynamically and allows the user to enter values into the array.
  2. Submit your completed program as part of this weeks exercises
  3. Use the following code to get started.
#include <iostream>
using namespace std;

int* makeArray(int length, int value);
void showArray(int values[], int length);

int main(void) {
    int arraySize, arrayValue;
    cout << "How large of an array do you want? ";
    cin >> arraySize;
    cout << "What value for each element? ";
    cin >> arrayValue;

    int* p = makeArray(arraySize, arrayValue);
    showArray(p, arraySize);
    delete [] p;

    return 0;
}

int* makeArray(int length, int value) {
    int* array = new int[length];
    for (int i = 0; i < length; i++) {
        array[i] = value;
    }
    return array;
}

void showArray(int values[], int length) {
    for (int i = 0; i < length; i++) {
        cout << values[i] << " ";
    }
    cout << endl;
}

Wrap Up

    Reminders

    Due Next: Exercise 11 (12/2/04)
    Sampler Project (12/7/04)

  • When class is over, please shut down your computer
  • There is no need to turn in this weeks exercises
  • Work on your project!

Home | WebCT | Announcements | Day Schedule | Eve Schedule
Course info | Help | FAQ's | HowTo's | Links

Last Updated: November 30 2004 @13:51:28