Borland
The new and delete Operators with multi-dimensional arrays (다차배열)
by leo21c
2011. 1. 18.
// ALLOCATE A TWO-DIMENSIONAL SPACE, INITIALIZE, AND DELETE IT.
#include <exception>
#include <iostream>
using std::cout;
using std::endl;
void display(long double **);
void de_allocate(long double **);
int m = 3; // THE NUMBER OF ROWS.
int n = 5; // THE NUMBER OF COLUMNS.
int main(void) {
long double **data;
try { // TEST FOR EXCEPTIONS.
data = new long double*[m]; // STEP 1: SET UP THE ROWS.
for (int j = 0; j < m; j++)
data[j] = new long double[n]; // STEP 2: SET UP THE COLUMNS
}
catch (std::bad_alloc) { // ENTER THIS BLOCK ONLY IF bad_alloc IS THROWN.
// YOU COULD REQUEST OTHER ACTIONS BEFORE TERMINATING
cout << "Could not allocate. Bye ...";
exit(-1);
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
data[i][j] = i + j; // ARBITRARY INITIALIZATION
display(data);
de_allocate(data);
return 0;
}
void display(long double **data) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << data[i][j] << " ";
cout << "\n" << endl;
}
}
void de_allocate(long double **data) {
for (int i = 0; i < m; i++)
delete[] data[i]; // STEP 1: DELETE THE COLUMNS
delete[] data; // STEP 2: DELETE THE ROWS
}
|