Warning 22.8.1.
The [] is important. It says that we are deleting an array, not just a single value. Forgetting the brackets is an error that can lead to undefined behavior (but fortunately, AddressSanitizer will catch this).
[size]
). The individual elements will be initialized by the default constructor if they are objects or uninitialized if they are primitive values (int, double, char, etc...). To initialize an array of primitive values all to 0, we can use an empty initializer list after the brackets:
// Allocate an array of 4 integers - uninitialized
int* data = new int[4];
// Allocate an array of 1000 integers - initialize to 0
int* data = new int[1000] {};
int numPersons = 10;
// Allocate an array of 10 Person objects - initialized with default constructor
Person* persons = new Person[numPersons];
data
is a local variable in main
βs stack frame. It points to the first element of the array, which is stored on the heap. The rest of the elements are stored in contiguous memory locations after the first element. All of the values are shown as random values because we did not initialize them.
delete[]
operator:
delete[] data;
delete[]
in the program above to delete
?mismatched-new-delete
.invalid-delete-address
.quizScores
. You will not use all the blocks.
new
and we put the size of the array after the variable name:
int data[1000];
int data[dataCount]
where dataCount
is a variable is a compile error as the compiler does not know how much space to allocate.
std::vector
and std::array
.