C .何时删除C风格数组以自由存储器

c++ . When to delete a C-style array to free memory

本文关键字:自由 存储器 风格 何时 删除 数组      更新时间:2023-10-16

我编写了一个代码,将千万转换为磅和石头。片段如下所示。

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可能是您想要的更好的选择,然后在此示例中使用newdelete

话虽如此,您将new -ED指针返回并将结果存储为float *weightoutput。要释放内存,您应该在完成delete [] weightoutput;时致电delete