1

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?

6
  • 7
    why not use a std::vector or std::array? edit: in this case you could actually return a std::pair<float, float> which would probably be clearer Commented Apr 17, 2017 at 18:59
  • Please see this question on returning arrays. You can still use a C-style array in the return and not need to use new[] at all (by using a struct). Commented Apr 17, 2017 at 19:06
  • Heck, why not just return a struct? Commented Apr 17, 2017 at 19:07
  • As a side point: what is x? what is z? what is y? These variable names give no meaning to the input or to the results. Unless you might need to have 10, 50, or even a 1000 values returned (i.e. if it is always only two values), a data structure with clear names (as well as a clear parameter name to the function) would make this code much clearer as to what it is doing. Commented Apr 17, 2017 at 19:16
  • @RyanP I agree. I was just experimenting with this option before I move to std::vector. Commented Apr 17, 2017 at 19:37

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Agreed, std::array is a better choice. I will be replacing 'new' with std::array, but curiosity got the better of me. So I wanted to try this before I move on.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.