I am having trouble implementing the given diagram (refer to pic link). the items that hold the values are suppose to be dynamically allocated and shaded boxes are pointers. then im suppose to deallocate memory accordingly.
p.s. its the 3rd class into the semester and me being fresh out of 'Intro to c++' feel lost in these ridiculous levels of indirection. Pointers(with multiple *'s), the heap, and the new / delete operators just fuck my mind. I need a tutor lol.
And as for the diagram. These are the instructions:
I) a) Declare and allocate memory to implement the diagram. That is, write C++ statements that will create what is shown in the diagram
The int a, b, c; may seem compact style, but it is better to keep things simple:
1 2 3
int a;
int b;
int c;
int * c { newint(18) };
This is ok. You do create two things in it: an integer and a pointer. Lets make that "unnecessary" simple too:
1 2 3 4 5 6 7 8
int * c { nullptr }; // create pointer
c = newint; // create integer
*c = 18; // change value of the pointed to object
// other code
delete c; // deallocate the integer objects memory
// if c is not used, then it does not be set nullptr
The deallocation is best done (here) in reverse order from the allocation.
The b has a type. It is indeed a pointer to pointer.
1 2 3 4 5 6 7 8 9 10 11 12
int * * b { nullptr };
// we did create an integer and did store its address into c
// now we should create a pointer to integer and store its address to b
b = newint* { nullptr };
// now we have a nameless pointer to integer that we can refer to with *b
// the *b should store the address of an integer that we have not created yet:
*b = new ...
// other code
delete *b; // the integer
delete b; // the pointer to integer
What remains is a and two other pointers. Two objects to delete.