[svlug] abt arrays in C
Erik Fears
strtok at softhome.net
Wed Apr 2 19:52:51 PST 2003
On Wed, Apr 02, 2003 at 06:40:44PM -0800, R Balaji wrote:
> Hi,
> Pardon me as this mail as nothing to do with Linux.
> I have a simple C programming doubt.
>
> void main(){
>
> int b[10];
> ____ = procedure();
>
> }
>
> ____ procedure(){
>
> int a[10];
> return _____;
> }
>
> I want to return array a from procedure () to array b
> in main. So please fill up the blanks. (____)
>
> Thanks
> Balaji.R
>
As matt pointed out, the only way to do this would be with malloc
(or a static array, but then you could only return one value at once).
Then you return a pointer to the memory you just created.
BAD:
type *proc()
{
type ret[5];
return ret;
}
This is bad because ret (the array)'s scope is within the proc function.
Once your code executes outside of the function, the array ret becomes
garbage.
GOOD:
type *proc()
{
type *ret;
ret = malloc(sizeof(type) * 5);
return ret;
}
-Erik
More information about the svlug
mailing list