如何在C ++中动态分配数组 [英] How to dynamically allocate arrays in C++
问题描述
我知道如何为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);
如何在C ++中达到同等水平?
具体来说,如何使用new
和delete[]
关键字?尤其是在创建/销毁链表节点或创建和销毁其大小由编译期间由变量确定的数组的情况下?
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?
推荐答案
L = new int[mid];
delete[] L;
用于数组(这是您想要的)或
for arrays (which is what you want) or
L = new int;
delete L;
用于单个元素.
但是使用向量或使用智能指针更简单,那么您不必担心内存管理.
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()
使您可以访问int[]
数组缓冲区,以后可以L.resize()
该向量.
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()
为您提供指向int[]
数组的指针.
L.get()
gives you a pointer to the int[]
array.
这篇关于如何在C ++中动态分配数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!