簡體   English   中英

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;
}     

我讀過多個帖子,如果您使用“ new”,則必須使用“ delete”來釋放內存。我的問題是,如何在此設置中刪除stones_pounds。 由於stones_pounds會一直使用到函數的最后一行,因此我認為我無法在函數內使用delete [] stone_pounds。 由於它不是全局變量,因此我也無法在主函數中將其刪除。 那么,如何使用delete []運算符釋放內存? 改變代碼結構以方便delete []運算符的唯一替代方法是嗎?

std::array可能是您想要的更好的選擇,然后在此示例中使用newdelete

如此說來,您將返回new指針並將結果存儲為float *weightoutput 要釋放內存,使用delete [] weightoutput; ,應該通過delete [] weightoutput;調用delete delete [] weightoutput;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM