0

so let's say there is a function int* coeff(int n) that returns array (or rather, address to array[0]). Now, in this function this array has length of let's say 5, but when I call it like: int* array=SomeObject->coeff(n); that size is lost, and I don't know how can I get it back again. Any help please?

user3369008
  • 105
  • 11

2 Answers2

1

If you actually return a locally declared you have bigger problem than "losing its size".

First of all you have to remember that arrays decays to pointers, and once it has done that you no longer have any information about the array, just the pointer. And the size of a pointer is the size of the pointer and not what it points to.

The bigger problem might be you returning a locally declared array. When a function returns all variables declared locally in it goes out of scope. So what does the returned pointer then point to?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

I assume your code looks something like this:

int* coeff(int n)
{
    int* a = new int[5];
    // ...
    return a;
}

I suggest using a vector instead of an array:

#include <vector>

std::vector<int> coeff(int n)
{
    std::vector<int> a(5);
    // ...
    return a;
}

You can always get the size of a vector by calling the .size() member function:

int main()
{
    std::vector<int> x = coeff(42);
    std::cout << x.size() << " elements in the vector!\n";
}
fredoverflow
  • 256,549
  • 94
  • 388
  • 662