CIS 150 Arrays and pointers

Objectives

  • Explain what a pointer is.
  • Declare and initialize/assign a value to a pointer variable.
  • Use & to get the address of a variable.
  • Use the dereference operator * to get the data pointed to by a pointer.
  • Explain the two different uses of the * (asterisk).
  • Use the new operator to dynamically allocate memory.
  • Use the delete operator to free dynamically allocated memory.
  • Use the delete[] operator to free dynamically allocated arrays memory.
  • Explain what a memory leak is.

Dynamic memory overview

  • Sometimes you don't know how much memory to set aside until a program is running. For those times, you need a way to dynamically allocate memory.
  • The new keyword is used to dynamically allocate memory.
  • The delete keyword is used to deallocate (free) memory.
  • The delete[] keyword is used to deallocate (free) array memory.
  • You can find the size of a variable or data type using sizeof(): sizeof(int)
  • Use * after a data type to specify a pointer to that type: int* means a pointer to an int
  • Use & before a variable to get the address of that variable in memory: &num means the address of num
  • Use * before a pointer variable to get or set the value of that memory location: *ptr = 5;

Allocating/deallocating memory

  • Allocate an int and save the pointer to it: int* ptr = new int;
  • Allocate an int array of size 7 and save the pointer to it: int* ar = new int[7];
  • Store 12 in the third element of the array: *(ar+2) = 12;
  • Triple the value of the last array element: *(ar+6) = 3 * *(ar+6);
  • Free the memory for the int: delete ptr;
  • Free the memory for the int array: delete[] ar;
  • Forgetting to deallocate (free) dynamically allocated memory causes a memory leak. That memory is not recoverable until the program stops ruinning and the operating system releases it. This is an especially difficult problem if the program is long running or if the leak is caused by code that runs many times.

Example of using pointers (w/o arrays)

int n = 7; int* ptr = &n; // now ptr points to n cout << n << endl; // displays 7 cout << *ptr << endl; // displays 7 *ptr = 12; cout << n << endl; // display 12 cout << *ptr << endl; // displays 12

Example of using pointers (with arrays)

int size = 5; int* ar = new int[size]; // dynamically allocates array of size integers for (int i=0; i<size; i++) { *(ar+i) = i * 2; // sets array to {0, 2, 4, 6, 8} } for (int i=0; i<size; i++) { cout << *(ar+i) << endl; // displays array elements } delete[] ar; // frees previously allocated memory