I know how to dynamically allocate space for an array in C. It can be done as follows:
L = (int*)malloc(mid*sizeof(int));
and the memory can be released by:
free(L);
How do I achieve the equivalent in C++?
Specifically, how do I use the new
and delete[]
keywords? Especially in the context of creating/destroying a linked list node, or creating and destroying an array whose size is given by a variable during compile time?
int* L = new int[mid];
delete[] L;
for arrays (which is what you want) or
int* 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 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(mid);
L.get() gives you a pointer to the int[] array.