Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

4. What does this code fragment do? int *p; int *q; p = new int( 6); q = new int

ID: 3620775 • Letter: 4

Question

4. What does this code fragment do?
int *p;
int *q;
p = new int( 6);
q = new int(15);
*p = *q;
delete q;
cout
<< "The value " << *p
<< " is stored at " << p << "." << endl
<< "Nothing valid now is stored at "
<< q << "." << endl;
q = new int();
cout
<< "The value " << *p
<< " is later stored at " << p << endl
<< "and the value " << *q
<< " is later stored at " << q << "." << endl;
delete q;
delete p;
The code fragment gives an example of dynamic memory allocation, a
term you can search out on the Internet. Here, the pointers p and q
(which are just variables suitable for storing addresses in) exist on
the stack as usual, but the two ints they point to exist in a different
region of memory called the heap. Trick question: what are the names
of the two ints? (answer: objects on the heap have no names, only
addresses). Write and thoroughly comment hw09_q04.cpp such that it
includes the above code fragment and compiles. Submit the thoroughly
commented hw09_q04.cpp.

Explanation / Answer

Hi, Hope this explains some stuff about pointer and helps you out with your program... #include using namespace std; /* Structure of a pointer (Example) int* p = new int(6); p-----------------*p 1000--------------2000 *********----------***** * 2000 *----------* 6 * *********----------***** &p == 1000 p == 2000 *p == 6 */ int main ( void ) { // two integer pointers which point // at nothing right now int *p = NULL; int *q = NULL; // allocate memory for 1 integer, store the value 6 // at new location and point p at this location p = new int (6); // for example, if printing p produces this value (006E4940), // then we know that this location in memory (006E4940) holds // the integer 6 // same with q... // allocate memory for 1 integer, store the value 15 // at new location and point q at this location q = new int(15); // de-reference p and assign value to q (de-referenced) // we are telling the memory location pointed to by q, // to store whatever integer is held by the memory location // pointed to by p. (this is referred to as de-referencing) // when we access a pointers contents. // Here (*q) is assigned 6 *p = *q; // de-allocate the memory given to q with the "new" operator // q still points to a memory location, but the memory is no // longer allocated. Thus, q should not be used anymore. delete q; cout
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote