Skip to content

Instantly share code, notes, and snippets.

@laprasdrum
Created April 23, 2013 11:33
Show Gist options
  • Save laprasdrum/5442860 to your computer and use it in GitHub Desktop.
Save laprasdrum/5442860 to your computer and use it in GitHub Desktop.
2 dimension array with range check
#include <iostream>
using namespace std;
class safetyArray {
char **array_;
int row_size_;
int column_size_;
public:
safetyArray(int row_size, int column_size);
~safetyArray() {
for (int i = 0; i < row_size_; i++) {
delete [] array_[i];
}
delete [] array_;
}
char &put(int row, int column);
char get(int row, int column);
};
safetyArray::safetyArray(int row_size, int column_size) {
array_ = new char*[row_size];
for (int i = 0; i < row_size; i++) {
array_[i] = new char[column_size];
}
if (!array_) {
cout << "cannot allocate memory." << endl;
exit(1);
}
row_size_ = row_size;
column_size_ = column_size;
}
char &safetyArray::put(int row, int column) {
if (row < 0 || row > row_size_ - 1) {
cout << "out of array's range" << endl;
exit(1);
}
if (column < 0 || column > column_size_ - 1) {
cout << "out of array's range" << endl;
exit(1);
}
return array_[row][column];
}
char safetyArray::get(int row, int column) {
if (row < 0 || row > row_size_ - 1) {
cout << "overflow error" << endl;
exit(1);
}
if (column < 0 || column > column_size_ - 1) {
cout << "overflow error" << endl;
exit(1);
}
return array_[row][column];
}
int main(int argc, const char * argv[])
{
safetyArray arr(2,5);
arr.put(1, 1) = 'o';
cout << "test " << arr.get(1, 1) << endl; // "test o"
arr.put(12, 12); // "out of array's range"
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment