CSCE 121 Chapter 18

From Notes
Jump to navigation Jump to search

« previous | Monday, November 8, 2010 | next »

Vectors and Arrays

Copy Constructor

vector v(3);
vector v2 = v;  // copy constructor
vector v3;
v3 = v;         // copy assignment

Default: one elements members are copied into the other (can cause memory leak if elem pointer is overwritten)

class vector {
  int sz;
  double* elem;
  public:
    vector(const vector&);  // override copy constructor
    vector& operator=(const vector& a); // copy assignment
};

vector::vector(const vector& a) : sz(a.sz), elem(new double[a.sz]) {
  for (int i = 0; i < sz; ++i) elem[i] = a.elem[i]
}

vector& operator=(const vector& a) {
  double* p = new double[a.sz];
  for (int i = 0; i < a.sz; ++i) p[i] = a.elem[i]
  delete[] elem;
  sz = a.sz;
  elem = p;
  return *this;  // return a self reference
}
  • Shallow copy: copy the pointer's address: a→[]←b
  • Deep copy: copy what the pointer points to: a→[] b→[]


Arrays

Not necessarily on the free store:

char ac[7];  // global array; "lives" forever in static store
int max = 100;
int ai[max];

int f(int n) {
  char lc[20];     // local array; "lives" until end of scope
  int li[60];
  double lx[n];    // error: local array size must be known at compile time.
                   // vector<double> lx(n); would work.
}


Wednesday, November 10, 2010


Address of: &

int* p = &b sets p to the address of the integer b

Arrays are (often) converted to pointers:

an array always points to its first element
Warning: arrays don't know their own size
void f(int pi[]) {  // equivalent to f(int* pi)
  int a[] = { 1, 2, 3, 4 };
  int b[] = a;  // error: copy is not defined for arrays
  int b = pi;   // error: array name is a non-changeable pointer
  pi = a;       // OK, but doesn't copy: pi now points to a's first element
  int* p = a;   // p now points to first element of a;
  int* q = pi;  // q now points to first element of a;
}

void g(int pi[], int n, char pc[]) {
  // identical to:  int* pi, int n, char* pc)
  char buf1[200];     // allocated from stack
  strcpy(buf1, pc);   // copies characters from pc into buf1; terminates when '\0' char is found
                      // let's hope that pc holds less than 200 chars

}

Only use pointers and arrays when allocating Free-store memory

even then, try to remember to delete allocated free-store variables

Initialization of Arrays

char ac[] = "Hello World!";   // '\0' automatically added to end of 12 chars (13 chars)
char* pc = "Howdy";          // pc points to array of 6 chars
char* pp = {'H', 'o', 'w', 'd', 'y', 0};  // another way to say the same thing

Vector: operator[]

Return an automatically dereferenced element using []:

double& operator[](int n){ return &elem[n]; }