Evil Science A whole load of stuff


C: Returning an array from a function

Recently I decided to learn C and have been diligently working my way through tutorials and websites, and since I'm more familiar with high level languages (C# for example) getting used to the more low level C is proving to be a challenge.

After getting to grips with the dreaded pointers I immediately ran into the problem of how to return an array from a function - the familiar methods used by anyone familiar with C# or VB.Net don't work, and attempts at implementing return unusual results. Basically, populating an array in a function and passing a reference to it is doomed to fail?it's a regular local variable,?with automatic duration, which means that it springs into existence when the function is called and disappears when the function returns. Passing a reference out of a function to a variable that has expired points to an junk.

After some googling, I found a?helpful document?that describes how to deal with the problem on http://c-faq.com, which describes in?the three methods of returning arrays from functions which, briefly,?are:

  1. The use of a static array within the function,
  2. Passing an array into the function and operating on it, and
  3. Creating an array in the function usign malloc.

All three methods have their own positives and negatives, but for the purposes on what I'm doing I'm going for the second one.

Filed under: Code Leave a comment
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.