Arrays and Dynamic Memory (new
)¶
Q) Which of the following as an advantage of using a vector
over an array?¶
a) Only vector can store more than one value.
b) Only vector can dynamically expand when adding new elements.
c) Only vector can store more than one type of value.
d) Only vector can be passed to functions.
Q) Function Prototype with Arrays¶
Which of the following is the best prototype for a function which adds up all values in an array of integers?
a) void sumArray(int data[], int size);
b) int sumArray(int data[]);
c) int *sumArray(int *pData);
d) int sumArray(int data[], int size);
Q) Problems with Pointers¶
Consider the following function:
const int DIE_SIDES = 6;
void printNRandomRolls(int n)
{
int *pData = new int[n];
for (int i = 0; i < n; i++) {
pData[i] = rand() % DIE_SIDES + 1;
}
for (int i = 0; i < n; i++) {
cout << pData[i] << ", ";
}
cout << endl;
}
Which of the following best describes the biggest problem with this function?
a) Out of bounds access.
b) Compile time error.
c) Memory leak.
d) Runtime error.
Answers¶
1 = b) Only vector can dynamically expand when adding new elements.
2 = d) int sumArray(int data[], int size);
3 = c) Memory leak.