-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
31 lines (23 loc) · 901 Bytes
/
main.cpp
File metadata and controls
31 lines (23 loc) · 901 Bytes
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
#include <cstdlib>
#include <iostream>
/* Dynamic memory allocation is easier in C++ than in C. */
int main(int argc, char *argv[]) {
int n = 5; // Static memory allocation is done like in C.
int *p = new int [n]; // Allocates dynamic int array of length n (without exception handling).
p[0] = 7; // Use a dynamic array as usual.
p[1] = 3;
std::cout << p[0] << " " << p[1] << std::endl; // gives '7 3'
delete [] p; // Disallocates the memory dynamically allocated at p.
int *q; // Dynamic allocation with exception handling can be done like this.
try {
q = new int [n];
}
catch (std::bad_alloc xa) {
std::cout << "Memory allocation failed." << std::endl;
return 1;
}
q[0]=1;
std::cout << q[0] << std::endl; // gives '1'
delete [] q;
return EXIT_SUCCESS;
}