Robert said:
Mark said:
Hi,
This might be a strange question but i would like to know how to
return an array from a function. Do you have to use pointers for this?
We answer this often here. Hopefully I get it right.
typedef struct ArrayContainer
{
int array[1024];
} ArrayContainer;
ArrayContainer manipulateArray(ArrayContainer *pArr)
{
pArr->array[0] = 0xDEADBEEF;
return *pArr;
}
int main(void)
{
ArrayContainter arrOne = { 0 };
ArrayContainter arrTwo = manipulateArray(&arrOne);
// arrTwo.array[0] is now set to 0xDEADBEEF;
return 0;
}
So it isnt really possible to return an array but only a structure?
It isn't possible to return an array, just as it isn't
possible to pass an array as an argument or to assign one
array to another. People sometimes write that arrays aren't
"first-class" data objects in C; this is the sort of thing
they mean.
A function can, however, return a struct or a union,
and a struct or union can contain an array (a struct can
contain more than one, if desired). So even though a
function cannot return an array as such, it can return
a "wrapped" array that the caller can then "unwrap."
Often, though, this subterfuge is unsatisfactory. It
only works with arrays whose size is fixed at compile time;
if your array's size is going to be computed at run time
you're out of luck. Also, if the array is large it will
probably take a lot of time to slosh all that data back and
forth.
The usual way around these difficulties is to give up
on the idea of returning an actual array, and instead return
a pointer to the first element of the array. Pointers and
arrays are very nearly interchangeable for most purposes;
Section 6 of the comp.lang.c Frequently Asked Questions
(FAQ) list <
http://www.eskimo.com/~scs/C-faq/top.html> has
a good exposition of the similarities and differences.
Questions 2.9 and 7.5 deserve your attention, too.