1int main()
2{
3 int size;
4
5 std::cin >> size;
6
7 int *array = new int[size];
8
9 delete [] array;
10
11 return 0;
12}
1int* a = NULL; // Pointer to int, initialize to nothing.
2int n; // Size needed for array
3cin >> n; // Read in the size
4a = new int[n]; // Allocate n ints and save ptr in a.
5for (int i=0; i<n; i++) {
6 a[i] = 0; // Initialize all elements to zero.
7}
8. . . // Use a as a normal array
9delete [] a; // When done, free memory pointed to by a.
10a = NULL; // Clear a to prevent using invalid memory reference.
11
1#include <iostream>
2#include <cstddef> // std::size_t
3
4int main()
5{
6 std::cout << "Enter a positive integer: ";
7 std::size_t length{};
8 std::cin >> length;
9
10 int *array{ new int[length]{} }; // use array new. Note that length does not need to be constant!
11
12 std::cout << "I just allocated an array of integers of length " << length << '\n';
13
14 array[0] = 5; // set element 0 to value 5
15
16 delete[] array; // use array delete to deallocate array
17
18 // we don't need to set array to nullptr/0 here because it's going to go out of scope immediately after this anyway
19
20 return 0;
21}
1int length = 50;
2int *array = new int[length]();
3// returns 50 length array of 0