Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Recall that in C++ there is no check on an array index out of bounds. However, d

ID: 639723 • Letter: R

Question

Recall that in C++ there is no check on an array index out of bounds. However, during program execution, an array index out of bounds can cause serious problems. Also, in C++ the array index starts at 0.

Design and implement the class myArray that solves the array index out of bound problem, and also allow the user to begin the array index starting at any integer, positive or negative. Every object of the type myArray is an array of the type int. During execution, when accessing an array component, if the index is out of bounds, the program must terminate with an appropriate error message. Consider the following statements:

myArray<int> list (5); // Line 1
myArray<int> myList (2,13); // Line 2
myArray<int> yourList (-5,9); // Line 3

The statement in Line 1 declares list to be an array of 5 components, the component type is int, and the components are: list[0], list[1],

Explanation / Answer

#include <iostream>
using namespace std;

class myArray {
public:
myArray(int n) {
start = 0;
end = n-1;
array = new int[n];
for (int i=0; i<n; i++) array[i] = i + 1;
}
myArray(int n, int m) {
start = n;
end = m - 1;
array = new int[m-n];
for (int i=0; i<m-n; i++) array[i] = start + i;
}
int operator[](int index);
private:
int start;
int end;
int *array;
};

int myArray::operator[](int index) {
if (index>=start && index<=end) {
return (array[index-start]);
}
cout << "Error: Index out of bound" << endl;
exit(1);
}

void main()
{
myArray list(5);
myArray myList(2,13);
myArray yourList(-5,9);
int i;

cout << "Elements in list: " ;
for (i=0; i<5; i++) cout << list[i] << " ";
cout << endl;
cout << "Elements in myList: ";
for (i=2; i<13; i++) cout << myList[i] << " ";
cout << endl;
cout << "Elements in yourList: ";
for (i=-5; i<9; i++) cout << yourList[i] << " ";
cout << endl;

cout << "Accessing list(6): " << endl;
cout << list[6];
/* Similar test for myList and yourList
cout << "Accessing myList(0): " << endl;
cout << myList[0];
cout << "Accessing yourList(10): " << endl;
cout << yourList[10];
*/
system("PAUSE");

return 0;
}