-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynamic_Allocation.cpp
More file actions
66 lines (58 loc) · 1.73 KB
/
Copy pathDynamic_Allocation.cpp
File metadata and controls
66 lines (58 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
using namespace std;
int main(){
cout << " ------- Variable ------- " << endl;
try{
int *p = new int;
*p = 1;
int *q = new int(5);
cout << *p << endl; // Output: 1
cout << *q << endl; // Output: 5
delete(p);
delete(q);
}
catch(bad_alloc &b){ // memory allocation failure
cout << "bad_alloc Exception" << endl;
exit(-2);
}
cout << endl << " ------- 1D Array ------- " << endl;
int arrLen = 10;
try{
int *dynArr = new int[10];
for (int i = 0; i < arrLen; ++i) { // access
dynArr[i] = i;
cout << dynArr[i] << " "; // Output: 0 ~ 9
}
cout << endl;
delete []dynArr;
}
catch(bad_alloc &){ // memory allocation failure
cout << "bad_alloc Exception" << endl;
exit(-2);
}
cout << endl << " ------- 2D Array ------- " << endl;
int row = 5, col = 10;
try{
int **dynArr2 = new int*[row]; // Allocate row first
for(int i = 0; i < row; ++i) { // Allocate col
dynArr2[i] = new int[col];
}
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
int index = i * col + j;
dynArr2[i][j] = index;
cout << dynArr2[i][j] << " "; // Output: 0 ~ 49
}
cout << endl;
}
for(int i = 0; i < row; ++i){ // Deallocate col first
delete []dynArr2[i];
}
delete []dynArr2; // Deallocate row
}
catch(bad_alloc &){ // memory allocation failure
cout << "bad_alloc Exception" << endl;
exit(-2);
}
return 0;
}