All lessons

8. Pointers

new and delete

0 of 5 activities0%

Reading 1

Heap allocation

Open

new type creates an object on the heap and returns a pointer. new type[n] creates an array of n elements.

Every new should eventually meet a delete (or delete[] for arrays). Forgetting delete leaks memory.

Prefer ordinary variables and arrays when the size is known and small. Use new when the size is decided at runtime.

int* p = new int(42);
cout << *p << endl;
delete p;

int n = 5;
int* a = new int[n];
a[0] = 7;
delete[] a;

Check 2

Matching delete

Open

Memory from new int[n] should be freed with

Fill in 3

Allocate

Open

The keyword that allocates heap memory is

Try it 4

Heap int

Open

Change the value stored via new.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Dynamic array sum

Open

Read n, then allocate an int array of size n with new. Read n integers, print their sum, then delete[] the array.

main.cpp
Loading editor…