=========================preview======================
(comp104)[2004](s)midterm~ckliu^_10127.pdf
Back to COMP104 Login to download
======================================================
The Hong Kong University of Science and Technology
COMP103: Programming Fundamentals II
Fall 2006, Lecture Section 1
Midterm Examination
Friday, November 03, 2006 6:00 C 8:00PM
Student Name: key Lecture Section:
Student ID: Lab Section/TA Name:
Instructions:
1. This is a closed-book, closed-notes examination.
2. Check that you have all 12 pages (including this cover page).
3. Write your name, student ID, lecture section, lab section/TA name on this page.
4. Please circle your answer.
5. Answer all questions in the space provided. Rough work should be done on the back pages.
6. You can use pencil to answer questions.
Question
Topic
Score
1
Pointer Basics
/14
2
Dynamic Objects
/9
3
Array
/5
4
Algorithms on Linked List
/21
5
Class Definition
/36
6
Class Usage
/15
Total
/100
/100
Question 1 : Pointer Basics (14 marks)
a) Given the following declarations,
int a;
int b[10];
char c;
int *d;
int *e;
char *f;
Indicate whether the following statement is correct or incorrect? (Please circle your answer) (10 marks)
a. *(b+3) = a; Correct Incorrect
b. c = c; Correct Incorrect
c. d = b + 2; Correct Incorrect
d. e = &b[0]; Correct Incorrect
e. f = new int[10]; Correct Incorrect
b) What is the output of the following program? (4 marks)
#include <iostream>
using namespace std;
int *F1(int *x){
*x *= 10;
return x;
}
int main(){
int m, n=10;
int *p, *q = &n;
m = (*q)+2;
p = F1(q);
*q += 5;
cout << n << " " << m << endl;
cout << *p << " " << *q << endl;
return 0;
}
Answer: 105 12
105 105
Question 2: Dynamic Objects (9 marks)
a) What is wrong in the following code? (3 marks)
#include <iostream>
using namespace std;
int main(){
int *p, *r;
p = new int;
r = new int;
*p = 1;
r = p;
return 0;
}
Answer:
It results in an inaccessible object (memory leak).
(The new object created for r cannot be accessed or deleted after r is set to p)
b) Read the following code and answer the questions. (6 marks)
#include <iostream>
using namespace std;
int main( ){
int x =20;
int* p;
p = new int;
*p = 30;
cout << *p << " " << x << endl;
delete p; //referred by question <i>
p = &x;
delete p;
cout << *p << " " << x << endl;
return 0;
}
<i> What is the usage of the first delete p? (3 marks)
Answer: it returns the memory space (pointed by p) that has been allocated using the previous new operation.
<ii> The program has an error. Identify the problem and state the reason. (3 marks)
Answer: the second delete p is invalid. It tries to return the memory space of a st