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 a single integer value 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 36). It should make a deep copy of the managed memory.
Hint 1.
m_myAddress is the memory address of the managed value. *m_myAddress is how you access the value from the heap. To get the value from other you can use other.getNum().
Hint 2.
You do not need a loop, but you still will need to allocate new memory for the copy and then copy the value from the original object to the new one.

Checkpoint 22.16.5.

The class NumberWrapper manages a single integer value 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 36). 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.
m_myAddress is the memory address of the managed value. *m_myAddress is how you access the value from the heap.
Hint 2.
You do not need a loop, but you still will need to allocate new memory for the copy and then copy the value from the original object to the new one.
You have attempted of activities on this page.