|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
You don't need a fax machine to get faxes. Get a fax-to-email fax number from CallWave. Try it free.
|
|
#1
|
|||
|
|||
|
Returning an array with a function
I am taking in an array with a function. When I am done with the function I want to return another array, can I do this?
Thanks, Jonathan Donaghe |
|
#2
|
|||
|
|||
|
I think the only way to do it is to pass in the array as a pointer or reference and let the function do its thing. I don't think you can explicitly return an array.
So you could have your function take in both arrays in the arguments, or (I'm not sure about this one), have it return the address or a pointer to a new array which was created on the heap. |
|
#3
|
|||
|
|||
|
When you take in the array, and modify it, you can return a new one by returning the pointer.
The passed in parameter should use the pointer syntax, and you should return the new array as a pointer. Make sure you allocate your new array on the heap using malloc, if you attempt to return a pointer to a static array declared in the function, your program will most likely dump core. |
|
#4
|
||||
|
||||
|
If you go Lord MJ's route, make sure you deallocate the array when you're finished with it, too.
__________________
Jon Sagara "Me fail English? That's unpossible!" |
|
#5
|
||||
|
||||
|
Just for kicks:
Since it's legal (according to Peter van der Linden's "Expert C Programming" book) to return a struct, you -can- return entire arrays, if you put them in a struct like this: Code:
struct mystruct {
int vector[20];
}
struct mystruct foo()
{
struct mystruct bar;
...do something nifty with bar...
return bar;
}
It's kind of a kludge though, and it you can't use it to handle dynamically-sized arrays. YMMV.
__________________
"A poor programmer is he who blames his tools." http://analyser.oli.tudelft.nl/ |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Returning an array with a function |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|