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?
Asked
Active
Viewed 100 times
0

user3369008
- 105
- 11
-
3Sounds like you probably want a `std::vector`. – chris Mar 08 '14 at 20:05
-
Before we continue, [read this.](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – jrok Mar 08 '14 at 20:05
-
Or if you want to stick with arrays, just pass another reference to the function. And let the function set that variable to the size of the array. – Engin Kayraklioglu Mar 08 '14 at 20:06
-
possible duplicate of [How to get the size of an Array?](http://stackoverflow.com/questions/874169/how-to-get-the-size-of-an-array) – Sebastian Hoffmann Mar 08 '14 at 20:06
-
Thanks, I'll read up on it – user3369008 Mar 08 '14 at 20:08
2 Answers
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