28D. Copying Structures

A structured value is a kind of value, and it can be stored and moved around like other values, such as integers. For example, suppose that PairOfInts is defined as follows.

  struct PairOfInts
  {
    int a;
    int b;
  };
Assuming that an int occupies 4 bytes, a value of type PairOfInts occupies 8 bytes. Statements
  PairOfInts x, y;
  x.a = 20;
  x.b = 40;
  y = x;
create two variables x and y of type PairOfInts, initialize x by storing its fields separately, and then copy the entire structure x into y.

Structure copies are done the same way no matter how you indicate the structures. For example,

  PairOfInts *p, *q;
  p = new PairOfInts;
  q = new PairOfInts;
  p->a = 20;
  p->b = 40;
  *q = *p;
copies structure *p into *q.

Shallow and deep copies

Shallow copies

The copy that you get from an assignment statement with a structure variable is a bit-for-bit copy, also called a shallow copy. To illustrate, let's create a Cell and copy it into another Cell. Notice that name is not a constant in this version of Cell.

  const int nameSize = 20;
  struct Cell
  {
    int item;
    char* name;
  };

  char str[nameSize];
  Cell *A, *B;

  strcpy(str,"grape");
  A = new Cell;
  A->item = 7;
  A->name = str;
  B = A;

The result looks like this.

As you can see, the array holding "grape" has not been copied. That makes sense because name has type char*, which is a pointer type, and the pointer has been copied from A into B. Doing

  B.name[0] = 't';
changes both B.name and A.name.

Deep copies

A deep copy does not do a bit-by-bit copy. Instead, when it sees a pointer in a structure, it copies what the pointer points to. If statement B = A; above were replaced by a deep copy, we would expect to get the following.

A common misconception is that

  B = A;
does a deep copy, and that any changes you make in B, including changing B.name[0], have no effect on A. Watch out for that. Draw pointer diagrams to ensure that you understand what you are getting.

C++ does not perform deep copies automatically. If you want a deep copy, you will need to write a function that performs the copy. For example, function copystr performs a deep copy of a string. Instead of copying a pointer, it copies what the pointer points to. (There are no pointers inside a string to worry about.)

Exercises

  1. Using type Employee from a prior exercise, suppose that variable Phil of type Employee has already been created and initialized. Write statements that create another Employee variable PhilCpy, and copy all of the information from variable Phil into variable PhilCpy. Answer