Array part of brain has been erased! - Help!

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi guys - it's been a while!
For the life of me, I can't remember how I passed an array back from a function call!!

I tried a few things last night but ended up using a global variable - which I do not want. Basically I have a function that reads some values from the outside world. It can from 4 to 63 bytes so I do not want to permanently allocate that amount of ram for a global variable.

Something like...

//pseudo code
main(){
 myarray[]=arrayfunction();
 do something with myarray;
}

myarray(){
 //read external stuff and create an array of random size
  function_array[]={10,23,45 ... n}
  return (function_array[])
}

One thing is I will know ahead of time how large the array is before calling the function.

I did this about 5 years ago and have since lost the code but I think I passed a pointer to the array from the function! But then again.. like I said, that part of may brain has been erased. Need to start wearing the foil hats again - or stop breathing the solder fumes :D

Thanks in advance
Tom

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Unfortunately, any "normal" local variables that you declare inside the function body will have been destroyed by the time that function exits. So, returning a pointer to any such variables will be nonsense, because the array it points to will no longer exist by the time it gets into the caller's hands.

You might try using malloc() to allocate space for the array in the heap, since heap allocations are persistent across function calls. A pointer to such an array will remain valid after being returned to the caller. However, your calling function would be obliged to free() that pointer once it no longer needs the data contained therein, otherwise your heap will rapidly collide with your stack and then all bets are off.

Alternatively, since you know beforehand how much space the array will need to take up, you might try doing things backwards: Let the caller allocate space for the array in its own stack, and then pass the subroutine a pointer to that array:

main()
{
   int my_array[whatever];
   arrayfunction(my_array, whatever); // Pass in 'whatever' too, so that arrayfunction() knows how much space it's allowed to play with.
}

void arrayfunction(int* array, int maxsize)
{
   // Fill in 'array', being careful not to go above 'maxsize' elements...
}

- Luke

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Nice!!

T