Re: A function returning string or pointer
- From: Chris Dollin <chris.dollin@xxxxxx>
- Date: Mon, 13 Nov 2006 15:17:28 +0000
svata wrote:
Hello to all,
as a result from my previous post I'm busy with splitting code into
functions.
The one problem ( out of many ) I encounter is how to properly
use/code a function which returns either array of characters(string) or
a pointer to this array.
You /must not/ return a pointer to an array which is a local
non-static variable of the function.
I read some articles, some other posts and come to this solution:
char *read_name(void){
static char item_name[11];
(fx:snip)
return item_name; /* return string in the form of character array */
}
So you /must not/ do this. The variable `item_name` evaporates when
the function returns, so the pointer to it isn't pointing anywhere
and any use of it gets you undefined behaviour -- which is a Very
Bad Thing.
You must return a pointer to store which will outlive the function
call: for example:
* a static array, usually a bad idea because different uses of the
function will share that array.
* mallocated store (which the using code will have to free)
* store passed in as an argument (so it's the caller's problem)
* mix as desired (carefully)
--
Chris "hantwig efferko VOOM!" Dollin
Meaning precedes definition.
.
- Follow-Ups:
- Re: A function returning string or pointer
- From: Chris Dollin
- Re: A function returning string or pointer
- References:
- A function returning string or pointer
- From: svata
- A function returning string or pointer
- Prev by Date: Re: Syntax for variable names spanning multiple lines in C
- Next by Date: Re: A function returning string or pointer
- Previous by thread: Re: A function returning string or pointer
- Next by thread: Re: A function returning string or pointer
- Index(es):
Relevant Pages
|
Loading