Re: return a string



Nascimento wrote on 29/04/05 :
How to I do to return a string as a result of a function. I wrote the following function:

char prt_tralha(int num)
{
        int i;
        char tralha[num];

tralha = "#";

This is not going to happen. You can't change the value of an array that way. You want strcpy().


        for( i = 0; i < num-1; i++ )
                strcpy(tralha, strcat(tralha,"#"));

Note that this is dangerous. The order of execution of the parameters is defined by the implementation. BTW, chances are that strcat() is called before strcpy(). Additionally, strcpy() only works with non overlapping strings. Your construction doesn't guarantee that.


(To the gurus : [C99] shouldn't the 'restrict' keyword used here by the compiler to generate some warning ?)

As a rule of thumb, don't use functions as a parameter to another function. In mosts cases, it hurts...

Finally, it seems to be a very complicated way of filling a string...


return tralha;

Returning the address of a local variable is, in most cases, a nonsense.


}

And I really like to use it, thus:

int main()
{
       printf("%s \n", prt_tralha(5));

       return 0;
}

But when I compile it, gcc shows this message:

tmp.c: In function `prt_tralha':
tmp.c:16: error: incompatible types in assignment

Ok, see above.

tmp.c:20: warning: return makes integer from pointer without a cast

Ok, I missed this one. Your function returns a char. You probably want a char *.


tmp.c:20: warning: function returns address of local variable

A common newbie error. The fact is that the last warning *is* the point. The address returned by a function must be valid after the function has terminated. Keep in mind that the duration of the local variables is limited to the bloc where it was defined. Meaning that outside of the bloc, it doesn't longer exist. Hence, its address is no longer valid. Returning its address is technically possible (say for debug purpose), but dereferencing it out of the function invokes an undefined behaviour.


There are 3 ways to correct your code.

- The worst : qualifying the array of char with 'static'. This deceiving solution looks simple and easy, but it can generate other more subtle bugs preventing from using the function in some cases (nested calls, mutual calls, recursion, preemptive threads etc.)

- Passing the address of an array. The caller is the game master. He defines the array, and ask the function to act on it through (address, size) parameters. (see fgets() for example)

- The function is allocating the array. The caller gives enough information so that the function is able to compute the requested size for the array. That done, it allocates the array (malloc()), process it, and returns its address. The duration of the allocated bloc is under the control of the program. It ends with an appropriate free().

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++

.



Relevant Pages

  • (patch for Bash) regex case statement
    ... Following up on my previous patch for regex conditional tests, ... /* Return an array of strings; ... int dollarflag, zeropad, compareflag; ... SHELL_VAR *var; ...
    (comp.unix.shell)
  • Re: Strategy or Iterator?
    ... It would be possible to write a class that returns the variations ... GNU General Public License for more details. ... protected CombinatoricOperator(Telements, int r) { ... An integer array backing up the original one to keep track of the ...
    (comp.lang.java.programmer)
  • (patch for Bash) regex conditional tests
    ... 'regex' are returned in array variable SUBMATCH. ... Skipping of positional parameters, array elements, string ... int dollarflag, zeropad, compareflag; ... SHELL_VAR *var; ...
    (comp.unix.shell)
  • Re: Warning on assigning a function-returning-a-pointer-to-arrays
    ... This declares pfunc as a function taking no arguments and returning ... int x, y; ... Presumably pfuncwill return a pointer to a single int, ... or the first of a sequence of "array 5 of int"s. ...
    (comp.lang.c)
  • Re: Memory Allocation Problem, please help
    ... typedef struct word_tag{ ... array is not an array. ... static int total_word_count; ... static int word_index(const char *word); ...
    (comp.lang.c)