Created
April 23, 2013 11:33
-
-
Save laprasdrum/5442860 to your computer and use it in GitHub Desktop.
2 dimension array with range check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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