DeepaK K C wrote:[color=blue]
>
> Could anybody tell me how to pass array to a function by value?[/color]
Passing an array to a function is actually impossible. Passing by
value is easy enough, since C doesn't support any other form of
parameter passing.
Even /trying/ to pass an array by value smacks of silliness
(investigate const for when you pass the address of an object
that you don't wish the function to modify).
But I'm afraid there /is/ a way to do this damn silly thing.
Wrap the array in a struct, and pass the struct by value.
On Thu, 17 Feb 2005 14:56:21 +0000, Thomas Stegen wrote:
[color=blue]
> DeepaK K C wrote:[color=green]
>> Could anybody tell me how to pass array to a function by value?
>>
>> -Deepak[/color][/color]
As others have said taken literally this is not possible, C does not
support the passing of arrays to functions at all. But you can create an
equivalent effect.
[color=blue]
> Three ways depending on how, why and where you want responsibilitie s to
> be for this.
>
> 1. Put the array in a struct.[/color]
If the array is already in a struct for other reason then this is fine.
But I've never come across a situation where this is a sensible thing to
do just for the purpose of passing the array "by value".
[color=blue]
> 2. Create a copy of the array in the calling function.[/color]
Possible. In that case the function interface allows the array in question
to be modified (if it doesn't modify it there's little point in passing by
value). So maybe some calling functions care about this while others don't.
[color=blue]
> 3. Create a copy of the array in the called function.[/color]
IMO this is the cleanest way. The corresponding parameter would be defined
as a pointer to const indicating to the caller that the array won't be
modified. memcpy() can be used to make the copy. Issues are determining
the size of the array (which is an issue anyway) and how to allocate space
for the copy.
DeepaK K C wrote:
[color=blue]
> Could anybody tell me how to pass array to a function by value?[/color]
[color=blue]
> cat main.c[/color]
#include <stdlib.h>
#include <stdio.h>
Comment