COS110 Tutorial 2 -26July2011-MEMO

COS110 Tutorial 2 -26July2011-MEMO - University of Pretoria...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 University of Pretoria COS110 Tutorial 2 MEMO-MEMO-MEMO Date: 27 July 2011 Time: 50 minutes Marks: 38 Student Surname and Initials:__________________________________________________ Student number:_______________________ Employee number:_____________________ Question 1: (Topic: dynamic memory allocation) [12 marks] Study the code below and answer the questions that follow: int main( void ) { const int INCREMENT = 5; int arrSize = 5; float *fValues = new float[arrSize]; int index; for (index = 0; index < arrSize; index++) fValues[index] = 0.5 * index; int newSize = arrSize + INCREMENT; float *newValues = new float[newSize]; //1. copy contents of array fValues to array newValues //2. set remaining values of array newValues to zero //3. de-allocate memory for array fValues //4. assign fValues to newValues and update arrSize variable //5. prevent dangling pointer cout << "array size is " << arrSize << endl; //output 1 for (index = 0; index < arrSize; index++) cout << "value at index " <<index << " is " << fixed << setprecision(1) << fValues[index] << endl; //output 2 return 0; }
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 Questions: a. Write the code to implement the steps shown as comments in function main. (8 marks) b. Fill the table below to show the output of the output statements labelled //output 1 and //output 2 (4 marks) Solutions: a. //1. copy contents of array fValues to array newValues (2 marks) for (index = 0; index < *size; index++) newValues[index] = fValues[index]; //2. set remaining values of array newValues to zero (2 marks) for (index = *size; index < newSize; index++) newValues[index] = 0; //3. de-allocate memory for array fValues ( 1 mark) delete [] fValues; //4. assign fValues to newValues & update size fValues = newValues; (2 marks) arrSize = newSize; //5. prevent dangling pointer (1 mark) newValues = NULL; b. (4 marks) Output statement in main.C
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/27/2012 for the course IT 101 taught by Professor Unsure during the Spring '11 term at University of South Africa.

Page1 / 6

COS110 Tutorial 2 -26July2011-MEMO - University of Pretoria...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online