JMU
Pointers and References in C/C++
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation for Java Programmers
Variables: Their Names, Values and Addresses
Variables: Their Names, Values and Addresses (cont.)
Pointing to Memory
Pointing to Memory (cont.)
Pointing to Memory (cont.)
Pointing to Memory (cont.)
Pointing to Memory (cont.)
Arrays
Arrays (cont.)
Arrays (cont.)
Arrays (cont.)
Arrays (cont.)
Pointer Arithmetic
Arrays and Pointers

An Example

cppexamples/memory/IndexOf.cpp
        /**
 *
 * An example that uses a char*
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
#include <iostream>
#include <string>
using namespace std;

/**
 * Find the index of the first occurence
 * of a character in a string.
 *
 * @param string_ptr A pointer to the string
 * @param lookFor    The character to look for
 *
 * @side-effects     None (Or are there?  Is string_ptr changed?)
 *
 * @return           The index of the first occurence of the 
 *                   character (0 based) or -1 if the character 
 *                   is not contained in the string
 */
int indexOf(char* string_ptr, char lookFor) {
  int index;

  index = 0;
  while ((*string_ptr != lookFor) && (*string_ptr != '\0')) {
    ++string_ptr;
    ++index;
  }

  if (*string_ptr == '\0')
    index = -1;

  return index;
}

/**
 * The entry point of the application
 */
int main(void) {
  char line[80];

  strcpy(line, "This is a line.\n");

  cout << indexOf(line, 'A') << "\n";
  cout << indexOf(line, 'i') << "\n";
  cout << indexOf(line, '\n') << "\n";
  cout << line;

}
        
References
References (cont.)
References (cont.)
Objects

An Encapsulation of a Simple Weight

cppexamples/memory/Weight.h
        #ifndef edu_jmu_cs_Weight_h
#define edu_jmu_cs_Weight_h

/**
 * A very simple weight class (used to demonstrate memory
 * allocation for objects)
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
class Weight {
 public:
  int pounds, ounces;

  /**
   * Explicit Value Constructor
   *
   * @param lbs   The number of pounds in this Weight
   * @param oz    The number of ounces in this Weight
   */
  Weight(int lbs, int oz);
};
#endif
        
cppexamples/memory/Weight.cpp
        #include "Weight.h"

Weight::Weight(int lbs, int oz) {
  pounds = lbs;
  ounces = oz;
}

        
Objects (cont.)