Kelvin@!!! said:
if i want a function to return me a string, how can I do it?
i know one method is by passing a string pointer to a function.
is there any implementation?
There are several approaches, none of them ideal.
You can make the caller pass in a pointer and length. This forces the
caller to guess how much space will be needed, and the function to
decide what to do if it's not enough.
You can return a pointer to a static object. This leaves the size
decision up to the caller, but can still cause problems if the result
won't fit. It also clobbers the result buffer on each call, so the
caller generally needs to copy the result to a safe location.
You can return a pointer to a result allocated by malloc(). This is
probably the most flexible method, but it requires the caller to
free() the result and risks memory leaks.
You *cannot* return a pointer to a local array variable. The array
ceases to exist when the function returns, and you're left with a
dangling pointer. The result is undefined behavior; in the worst (and
most common) case, it will appear to work properly at first, and fail
only at the most inconvenient possible moment.
I once implemented a variant of the static buffer method. The
function declared an array of half a dozen or so static buffers, with
a static index cycling through them. This allowed several results to
be used simultaneously, but the seventh call would clobber the result
from the first call. I'm not sure I'd recommend this; you have to be
as careful as with the single static buffer, but any errors won't show
up as soon.