1
h06
CS16 F19
Name:
(as it would appear on official course roster)
Umail address: @umail.ucsb.edu section
Optional: name you wish to be called
if different from name above.
Optional: name of "homework buddy"
(leaving this blank signifies "I worked alone"

h06: Chapter 7 and 10: Pointers

ready? assigned due points
true Thu 10/31 09:00AM Thu 11/07 11:59PM

You may collaborate on this homework with AT MOST one person, an optional "homework buddy".

UPLOAD A PDF OF YOUR ANSWERS TO GRADESCOPE BEFORE THE DUE DATE. ASSOCIATE EACH QUESTION WITH A SPECIFIC PAGE IN YOUR HOMEWORK AT THE TIME OF SUBMISSION. There is NO MAKEUP for missed assignments;


Please:

  • No Staples.
  • No Paperclips.
  • No folded down corners.

Read Chapter 7.1 - 7.2 up to page 397. Also read this handout on Pointers and Memory: http://cslibrary.stanford.edu/102/PointersAndMemory.pdf Upload your answers as a pdf to the h06 assignment on gradescope.

PLEASE MARK YOUR HOMEWORK CLEARLY, REGARDLESS OF IF YOU WRITE IT OUT IN INK OR PENCIL!

1.(2 pts) What is the output of the following code? If there’s an error that will not allow an output, point it out. Briefly justify your answer.

int arr[5];
for (int i = 0; i < 5; i++) {
  if (i < 3) arr[i] = 'a';
  else arr[i] = 'z';
  cout << arr[i] << endl;  }

2.(2 pts) What is the output of the following code? If there’s an error that will not allow an output, point it out.

int arr[7] = {5};
for (int i = 0; i < 7; i++)
  cout << arr[i] + i <<" ";

3.(2 pts) What is the output of the following code? If there’s an error that will not allow an output, point it out.

int codes[] = {44, 66, 83, 973, -977};
for (int count : codes) {
  if ( (count/2) < 50 )
    cout << count << endl;
  else cout << "invalid" << endl; }

4.(8 pts) Write the definition of a function named ‘reverse’ that takes two parameters: an integer array and the number of elements of the array. The function should reverse the order of elements of the array. The function should not return anything. See below for an example of expected outcome when the reverse function is called:

int nums[] = {10,20,30,40,50};
reverse(nums, 5);// The order of elements should be reversed after this
for(int i=0;i<5;i++)
   cout<< nums[i]<<" "

The output of the above code should be: 50 40 30 20 10

5.(2 pts) List two reasons why you might choose to pass parameters to a function by address or reference, rather than by value in your C++ programs.

6.(4 pts) Draw a pointer diagram to demonstrate how the state of memory changes as the following code is executed. Cross out old values/arrows and draw new ones. Is this program likely to result in a segmentation fault? If so, why?

   int num = 10, *ptr1 = &num, *ptr2=0;
   if (ptr2) ptr1 = ptr2;
   else if(ptr1) ptr2 = ptr1;
   (*ptr1)++;