Re: A function returning string or pointer



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.

.



Relevant Pages

  • Re: Correct type for array indices
    ... >>Suppose I have a pointer to some structures. ... >>type to store the number of entries in that array, ...
    (comp.lang.c)
  • Re: array of pointers
    ... > array of pointers is neccesary more RAM memory to store these datas. ... derived type has a pointer component. ... upper bound for each rank, although that is at least largely redundant. ...
    (comp.lang.fortran)
  • Re: [RFC] defer skb allocation in virtio_net -- mergable buff part
    ... have an array of pages per list element instead of just one pointer ... store an array of page pointers in one of the free ...
    (Linux-Kernel)
  • Re: simple array question
    ... I am trying to create an array the same as the char *argvthat is passed ... I need to store a pointer to and integer in one of the elemets, ...
    (comp.lang.c)
  • Re: char **argv & char *argv[]
    ... "pointer to pointer to char". ... >> pointer)) pointing to the first element of an array. ... so we have to start adding more context. ... type "pointer to char", rather than "array MISSING_SIZE of char". ...
    (comp.lang.c)

Loading