How to dynamically allocate arrays in C++

L = new int[mid]; 
delete[] L;

for arrays (which is what you want) or

L = new int;   
delete L;

for single elements.

But it’s more simple to use vector, or use smartpointers, then you don’t have to worry about memory management.

std::vector<int> L(mid);

L.data() gives you access to the int[] array buffer and you can L.resize() the vector later.

auto L = std::make_unique<int[]>(mid);

L.get() gives you a pointer to the int[] array.

Leave a Comment