CS 70

Array Example

Destruction and Deallocation for Arrays of Primitives

  • LHS Cow speaking

    Oh, we forgot to talk about destruction and deallocation for arrays!

  • RHS Cow speaking

    That's okay. It's the same as any other variable.

Destruction and deallocation both happen for arrays of primitives the same way that the happen for individual primitives:

  • At the closing } of the declaring block, the variable is destroyed. Nothing happens to the values (because they're primitives) but the name of the array is no longer valid to use.
  • At the closing } of the function, all of the memory for the variable is deallocated.

Let's Try an Example!

  • LHS Cow speaking

    Behold! The world's most convoluted way to multiply a number by three:

int multiplyByThreeTheHardWay(int multiplier)
{
    constexpr size_t MULTIPLICAND = 3;
    int scratchSpace[MULTIPLICAND];

    for (size_t i=0; i<MULTIPLICAND; ++i) {
        scratchSpace[i]=multiplier;
    }

    int product=0;

    for (size_t i=0; i<MULTIPLICAND; ++i) {
        product += scratchSpace[i];
    }

    return product;
}

int main()
{
    int magicNumber = multiplyByThreeTheHardWay(14);
    cout << magicNumber << endl;
    return 0;
}

See if you can walk through this code and draw the memory diagram!

New memory diagram rule:

  • When a variable is declared constexpr, draw a padlock next to its name in the diagram.
  • The padlock indicates that you can't use this name to change the value at this spot.
  • LHS Cow speaking

    If you ever find yourself using a padlocked name to change a value, something is wrong!

Diagram Check

Did you try to draw the diagram?

  • RHS Cow speaking

    We're not done with the lesson yet, but let's head back up to the parent page to see our progress and take a break!

(When logged in, completion status appears here.)