Reputation: 6051
Let's say we havew a function that returns an array.
int *theFunction()
{
int a[]={1,2,3,4,5};
return a;
}
I want to store the result of the function in a pointer.
int *a=theFunction();
How do I print the array, is it even possible? The length of the array isn't known, is there a way to find it?
Upvotes: 1
Views: 4316
Reputation: 32797
You cant print an array
when its size
is unknown
You can get around this problem by
1>providing a sentinal value i.e the value that would denote the end of the array.
Let us consider -1
to be the sentinal then
int a[]={1,2,3,4,5,-1};
^
|->-1 would denote the end of array
But this solution would fail if one of your value seems to be -1
OR
2>Use a struct to denote the size and the array content
struct list
{
int *values;//the array of values
int size;//size of the values array
}
Also dont return a pointer to value that has local scope..i.e in your case the local value is a
..As soon as you get out of the method a is destroyed..further access to this a
after the method returns is an error
Upvotes: 2
Reputation: 1034
First, never ever return pointers to local variables. Allocate that array on the heap.
As for returning the size of the array, you can have the function return a structure that contains both the pointer and the array size.
Another method is to have the caller pass a reference to a size variable that the callee modifies.
Upvotes: 3
Reputation: 2335
How hard it is to also return the length of the array as an out param? If you have any special number in the array that marks the end, you could use that. Otherwise there is no way you can find the length of the array just with a pointer. And about returning a stack pointer outside the function, it may lead to crash.
Upvotes: 1
Reputation: 7421
No.
You'll need to delineate the array with a value you know won't come up, or pass a pointer to the function which will populate it with the size.
But you're also returning a pointer to data on the stack; that won't work either.
Upvotes: 4
Reputation: 23699
a
is a local variable, you can't acceed to its value out of theFunction
function.
Anyway, to print an array without its size, you have to add a delimiter (a particular value, for instance).
Upvotes: 2