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...
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++