C .何时删除C风格数组以自由存储器
c++ . When to delete a C-style array to free memory
我编写了一个代码,将千万转换为磅和石头。片段如下所示。
float *weightoutput = weight_conversion(weight);
函数如下。我使用了C风格的数组,
float* weight_conversion(float x){
float *stones_pounds = new float[2]; //C-style array
float z, y;
z = x*0.15747304441776971; // (1 stone = 6.3503 kilo)
y = x*2.2026; // (1 kilo = 2.2026 pounds)
stones_pounds[0] = z;
stones_pounds[1] = y;
return stones_pounds;
}
我已经阅读了多个文章,如果您使用"新",则必须使用"删除"以释放内存。我的问题是,我如何在此设置中删除Stones_pounds。由于stones_pounds一直使用到函数中的最后一行,因此我认为我不能在函数中使用delete [] stones_pounds。由于它不是全局变量,因此我也无法在主函数中删除它。那么,如何使用删除[]操作员释放内存呢?是否唯一更改代码结构的替代方案来促进删除[]运算符?
std::array
可能是您想要的更好的选择,然后在此示例中使用new
或delete
。
话虽如此,您将new
-ED指针返回并将结果存储为float *weightoutput
。要释放内存,您应该在完成delete [] weightoutput;
时致电delete
。
相关文章:
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 将自由函数绑定为类成员函数
- 静态数组的自由动态数组
- 调试和自由执行中的信号处理
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 为什么成员函数地址离自由函数这么远?
- 如何理解C++中链表的自由列表实现?
- 检测到堆栈粉碎,中止,OpenGl 自由过剩
- 创建 OpenCV 非自由版本 v4.3 时出错,可折叠.cpp错误 C2039、2605
- 如何使用模板元编程在自由函数C++链接两个不相关的类
- C++ 20 中的运算符 == 和 <=> 应该作为成员还是自由函数实现?
- 瓦尔格林德错误 - 地址0x0不是堆叠的 malloc'd 或自由的
- 如何在共享库中保留静态库中的自由函数
- libuv - 自由写入缓冲区
- Valgrind 声称内存释放中的自由空间太多
- 在C++项目中管理自由函数有哪些好的做法?
- 正交项目自由型开放
- 使用自由函数作为LPOVELAPPED_COMPLETION_ROUTINE
- 将C#结构的存储器大小与C 结构匹配
- C .何时删除C风格数组以自由存储器