"Remo D." <rdentato> writes:
> Hi! I'm writing a function that returns an array of (at maximum) 64
> pointers to char. I have thought of three possibility:
>
> - The caller p***** a pointer to a previously allocated array of 64
> pointers. Similarly to sprintf(), the caller is entirely responsible
> for handling the memory. The drawback is that my function will have to
> rely on the correctness of such pointer to work properly.
That's probably ok if you clearly do***ent the requirement for the
caller.
> - My function allocates the array and returns it. This is similar to
> strdup(). Here I will have to rely on the caller function to properly
> free the array, which is something I'm not very comfortable with.
Again, do***ent the requirement. It does make your function a little
harder to use, but not impossibly so.
> - I'll have a "static char *ret[64]" in my function and will return
> ret. I've not been able to think of a library function that behaves
> this way, so I guess it's not reccomended. The good is that I'm free
> from allocation/freeing problem. The bad is that the return values
> will be overwritten at each call; if the user wants to keep the return
> values for subsequent use he has to copy and store them somewhere.
> Another drawback is that it consumes memory even if the function will
> never be called.
Several functions in the standard library return pointers to static
objects: setlocale, localeconv, getenv, strerror, asctime, ctime (I
don't know whether that's a complete list).
> In my specific case, I was leaning toward the third option but I'd
> like to hear your opinion on pitfalls, things that I've missed or
> alternative approaches that could work better.
Since your list is limited to 64 elements, you could return a
structure containing 64 pointers and an integer that specifies how
many of them are valid. Since structures are passed and returned by
value [*], this is simpler, but it could be inefficient both in time
(copying the data rather than passing a pointer to it) and in space
(since you allocate the entire structure even if fewer than 64
elements are valid).
[*] All types are passed and returned by value; the difference is,
unlike for arrays, (a) you can declare a struct parameger, and (b)
there's no implicit conversion to pointer for structs.
--
Keith Thompson (The_Other_Keith) <kst-u@[EMAIL PROTECTED]
>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"


|