Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically allocate arrays in C++

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?

like image 452
thematroids Avatar asked Feb 21 '16 04:02

thematroids


1 Answers

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<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.

like image 131
Jts Avatar answered Oct 07 '22 17:10

Jts