Re: return a string





Nascimento wrote:
> Hello,
>
> 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 = "#";
> for( i = 0; i < num-1; i++ )
> strcpy(tralha, strcat(tralha,"#"));
>
> return tralha;
> }
>
> 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
> tmp.c:20: warning: return makes integer from pointer without a cast
> tmp.c:20: warning: function returns address of local variable

You seem to be confused about several points. The
comp.lang.c Frequently Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

covers some of them: Section 6 will help you understand
gcc's first complaint, Question 8.1 explains the second,
and Question 7.5 covers the third.

However, gcc did not catch all your errors. One that
it didn't catch is the strcpy() call: you are passing it
two strings that overlap, but strcpy() requires the source
and destination areas to be distinct. When you try to use
strcpy() on overlapping strings, anything at all might
happen. (Since the overlap is "perfect" -- the source and
destination are exactly the same string -- the strcpy()
call is pointless anyhow. I think this goes back to your
misunderstandings about strings; see FAQ section 8.)

Read the FAQ, re-read your textbook, and start over.
Good luck!

--
Eric.Sosman@xxxxxxx



.



Relevant Pages