如何在 C++ 中动态分配数组 [英] How to dynamically allocate arrays in C++

查看:75
本文介绍了如何在 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++ 中实现等价的?

具体来说,我如何使用 newdelete[] 关键字?特别是在创建/销毁链表节点,或在编译时创建和销毁其大小由变量给定的数组的上下文中?

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;

对于单个元素.

但是使用vector更简单,或者使用smartpointers,那么你就不用担心内存管理了.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆