Skip to main content

Section 22.16 Exercises

Checkpoint 22.16.1.

Write a function getPI that allocates a double on the heap, initializes the memory (or assigns it) to hold 3.14, and returns a pointer to the allocated memory.

Checkpoint 22.16.2.

Write a function makeArray that allocates an array of 3 double on the heap, sets them to 1.1, 2.2, and 3.3, then returns a pointer to the array.
Hint.
You can use {value, value, value} to initialize the array. Or you can do assignments to the three elements after creating it.

Checkpoint 22.16.3.

Write a function makeBigArray that allocates an array of 100 double on the heap and sets them all to 5.0. It should then return a pointer to the array.
Hint.
You will almost certainly need a loop to set all the elements of the array.

Checkpoint 22.16.4.

The class NumberWrapper manages an array of two integer values on the heap. (Which is admittedly a kind of silly thing to do.)
Implement the copy constructor for NumberWrapper. It is declared inside the class, you will implement it outside the class (at line 42). It should make a deep copy of the managed memory.
Hint.
Make sure to do a deep copy. Allocate your own array and then copy the values one by one from the original.

Checkpoint 22.16.5.

The class NumberWrapper manages an array of two integer values on the heap. (Which is admittedly a kind of silly thing to do.)
Implement the assignment operator NumberWrapper. It is declared inside the class, you will implement it outside the class (at line 42). It should make a deep copy of the managed memory.
Don’t forget to check for self-assignment! If you have a use after free error, it could be due to not handling self-assignment correctly.
Hint 1.
Make sure to check for self assignment, delete your old memory, allocate new memory, and copy the values.
Hint 2.
You need to return *this.
You have attempted of activities on this page.