CS 210 – Fundamentals of Programming I
Spring 2007 – In-class Exercise for 4/23/07 & 4/24/07


Name(s):


(5 points) Complete this exercise in pairs. The purpose of this exercise is to work with pointers and dynamic arrays.


For the following program, draw the memory picture created by the program at the points indicated in the comments (under the comment) and predict the output. Then create a project and type in the source code, and build and run the program. (Please do type in the code. You will remember more than if you just copy and paste the code into the project.) Observe the actual output and explain any discrepancies between your prediction and the actual output. When you have completed this exercise, hand in these answer sheets


Program pointer3.cpp: Memory pictures:


#include <iostream>
using namespace std;

const int MAX = 10;

int main ()
{
   int *ptr1,  // for arrays.
       *ptr2;                      // (a.) what it the picture here






   ptr1 = new int [MAX];           // (b.) what is the picture here







   for (int i = 0; i < 6; i++)
   {
      ptr1[i] = i * 10;
   } // end for
   ptr2 = ptr1;                    // (c.) what is the picture here




   for (int j = 0; j < 6; j++)
   {
      cout << *ptr2 << endl;  
      ptr2++;
   } // end for
                                   // (d.) what is the picture here
                                           (after the for loop)





   delete [] ptr1;
   return 0;
} // end main


Predicted output: Actual output:






Explain any discrepancies:





04/20/07 2