0

I have a function like:

function(double* numbers)

I know that if I know the size of the numbers array, I can then do

double* numbers = new double[size];
function(numbers)

This will return the value in numbers correctly, however, now I don't know the size of numbers, I still want to use function function, which is a third party library function which I don't want to change, is there a way to get the array out without knowing the size of array?

jotik
  • 17,044
  • 13
  • 58
  • 123
  • 1
    No there isn't. – Sam Varshavchik Jan 30 '17 at 17:36
  • You simply use a `std::vector` instead of a raw pointer. – πάντα ῥεῖ Jan 30 '17 at 17:36
  • It depends entirely on what `function` does with the variable and the contract it provides. – clcto Jan 30 '17 at 17:36
  • 2
    Only the 3rd party library will know, how it communicates the array length. Since it doesn't appear to take an explicit length argument, the array must be either implied, or terminated by some sentinel value. – IInspectable Jan 30 '17 at 17:36
  • @Rusheng Zhang A function declared like this function(double* numbers) knows nothing about the size of the array used as an argument. So you should not bother about this because the function itself does not bother about this.:) – Vlad from Moscow Jan 30 '17 at 17:37
  • @VladfromMoscow so how do I retrieve this value? – Rusheng Zhang Jan 30 '17 at 17:41
  • @RushengZhang Why do you bother about the function that you did not write?:) – Vlad from Moscow Jan 30 '17 at 17:46
  • @VladfromMoscow This function returns an array to the variable numbers which I need to pass into and retrieve the value. So I'll have to need to pass something there and get the value. The standard way is to pass a double* numbers = new double[size]; into the function but now I don't know the size. – Rusheng Zhang Jan 30 '17 at 17:56
  • @RushengZhang One more you should not bother how the function processes arrays passed to it. Just read the description of the function and call it accordingly its description. It is not your problem. It is a problem of the author of the library where the function is called from. – Vlad from Moscow Jan 30 '17 at 18:02
  • A workable technique would be to reserve element 0 of the array as the array size. I don't like it. jotiks suggestion is much better. – EvilTeach Jan 30 '17 at 18:30

1 Answers1

0

No, there's no standard way to retrieve the size of the array at run time from a mere pointer. I suggest you either use std::array for fixed-size arrays, or std::vector for variable-length arrays. An less safe alternative would be to pass the size of the array together with the pointer.

jotik
  • 17,044
  • 13
  • 58
  • 123