«

»

Jul 11

References and Pointers (C++)

Inspired by C++ Primer, Fifth Edition

A reference refers to (is another name for) another object. Any operation on the reference actually operates on the object to which the reference is bounded.

int ivalue = 128;
int &refValue = ivalue;        
int &refValue;                // error: a reference must be initialized

A pointer is an object itself (unlike a reference) and “points to” another object.

int *intPtr;                 // Pointer to an int
double *dPtr;                // Pointer to a double

Pointers can have four states: 1) It can point to an object, 2) It can point to the location just following the end of an object, 3) null pointer, 4) Invalid (not one of aforementioned states)

The address-of operator (&) is used to get the address of an object:

int intVal = 100;
int *intPtr = &intVal;

The dereference operator (*) is used to access the value “pointed to” by the pointer:

int ival = 100;
int *intPtr = &ival;
cout << *intPtr;             // outputs the value pointed at by intPtr

The following code illustrates how to pass a vector of integers by reference to a function:

#include <iostream>
#include <vector>

using std::vector;
using std::cin;
using std::cout;

int MaxPairwiseProduct(const vector<int>& numbers) {
  int result = 0;
  int n = numbers.size();
  for (int i = 0; i < n; ++i) {
    for (int j = i + 1; j < n; ++j) {
      if (numbers[i] * numbers[j] > result) {
        result = numbers[i] * numbers[j];
      }
    }
  }
  return result;
}

int main() {
    int n;
    cin >> n;
    vector<int> numbers(n);
    for (int i = 0; i < n; ++i) {
        cin >> numbers[i];
    }

    int result = MaxPairwiseProduct(numbers);
    cout << result << "\n";
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>