C/C++使用malloc为结构体数组分配内存(及free释放内存)的三种方法

template<typename Key, typename Value>
struct Node {};

为例,试创建有n个Node类型的node的数组。

方法一(nodes[i]为指针):

struct Node<int, int> *nodes[n];
for (size_t i = 0; i < n; i++)
    nodes[i] = (struct Node<int, int>*)malloc(sizeof(struct Node<int, int>) * n); 

使用

for (size_t i = 0; i < n; i++) {
    std::free(nodes[i]);
}

释放nodes的内存。

方法二(nodes[i]为指针):

struct Node<int, int> **nodes = (struct Node<int, int>**)malloc(sizeof(struct Node<int, int>*) * n);
for (size_t i = 0; i < n; i++)
    nodes[i] = (struct Node<int, int>*)malloc(sizeof(struct Node<int, int>));

使用

for (size_t i = 0; i < n; i++) {
    std::free(nodes[i]);
}
std::free(nodes);

释放nodes的内存。

方法三(nodes[i]为结构体struct):

struct Node<int, int> *nodes = (struct Node<int, int>*)std::malloc(sizeof(struct Node<int, int>) * n);

 使用

std::free(nodes);

释放nodes的内存。如果将nodes插入到类中,注意应考虑类的析构函数。

错误方法:

struct Node<int, int> (*nodes)[n] = (struct Node<int, int>(*)[n])std::malloc(sizeof(struct Node<int, int>) * n);

(参考How to dynamically allocate a 2D array in C?malloc申请二维数组的四种方法

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ayka

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值