I wrote a code to convert kilos to pounds and stone. A snippet is shown below.
float *weightoutput = weight_conversion(weight);
with the function as below. I used a C-style array,
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;
}
I have read in multiple posts that if you use "new", you have to use to "delete" to free up memory.The question I have is, how could I delete stones_pounds in this setup. Since stones_pounds is used till the last line within the function in return, i don't think i can use delete [] stones_pounds within the function. Since it is not a global variable, i cannot delete it within the main function as well. So how do I go about using the delete[] operator to free up memory? Is the only alternative changing the structure of the code to facilitate the delete[] operator?
std::array
is probably a better choice for what you want then using new
or delete
in this example.
With that said, you return the new
-ed pointer and store the result as float *weightoutput
. To free the memory, you should call delete
on that when you're done with it via delete [] weightoutput;
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.