{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

discussion8_no_ans

# discussion8_no_ans - CS31 Introduction to Computer Science...

This preview shows pages 1–4. Sign up to view the full content.

CS31: Introduction to Computer Science I Discussion 8 May 20, 2011 TA: Paul Wais ( [email protected] ) Discussion Section 1L Information TA: Paul Wais ( [email protected] ) Office Hours: Thursdays 11:30am - 1:30pm in Boelter Hall 2432 Discusion Website: http://www.cs.ucla.edu/ ˜ pwais 1 Survey! If you haven’t already, please take a moment after class to fill out a brief survey rating this Disc. Section: http://goo.gl/J6uGA 2 Pointer Practice What does the following code print? 1 double * findMin( double * a, int n) 2 { 3 if (n > 0) 4 { 5 double minVal = a[0]; 6 double * min = &a[0]; 7 for ( int i = 1; i < n; i++) 8 { 9 if (a[i] < minVal) 10 { 11 minVal = a[i]; 12 min = &a[i]; 13 } 14 } 15 return min; 16 } 17 else 18 return NULL; 19 } 20 21 int main() 22 { 23 double nums[] = {0.1, 0.2, 0.4, 0.001, 0.8}; 24 double * min; 25 min = findMin(nums, 5); 26 cout << * min; 27 } Answer: 1

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Suppose we were to change the line in main() min = findMin(nums, 5); to min = findMin(nums, 0); What would the new program print? Answer: 2.1 Pointer Pass-by-Reference and Iteration with Pointers Last time we discussed that when a function gets called with a pointer, the function actually gets a copy of the pointer’s address. By default, pointer arguments are pass by value. It’s also possible to pass pointers by reference (like any other parameter) using the ’&’ symbol. Let’s see an example. Suppose we changed main() in the above program to: 1 int main() 2 { 3 double nums[] = {0.1, 0.2, 0.4, 0.001, 0.8}; 4 double * min; 5 setMin(nums, 5, min); 6 cout << * min; 7 } Write a function setMin() that behaves the same as findMin() except that setMin() assigns a pointer argument to the minimum value of an array. Now, rewrite setMin() to use no square brackets. 2
Finally, rewrite setMin() without using any local variables of type int (other than the parameter n). 2.2 Pointers and Scope Local variables only ’exist’ inside pairs of braces. Consider the example below; what does it print?

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}