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
Thanks,
Nascimento
#include <stdio.h>
#include <stdlib.h>
const char * string_function(void)
{
static const char * my_text = "My text";
return my_text;
}
int main(void)
{
printf("%s\n", string_function());
return EXIT_SUCCESS;
}
Fundamentally, you pass a pointer to a string; not
the string.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
.
Relevant Pages
- Re: variadic arithmetic, boolean operators
... containers (lists, vectors, arrays, etc.) to each function. ... int sum(int * array_of_integers, ... C++ Faq: http://www.parashift.com/c++-faq-lite C Faq: http://www.eskimo.com/~scs/c-faq/top.html alt.comp.lang.learn.c-c++ faq: ... Other sites: http://www.josuttis.com -- C++ STL Library book http://www.sgi.com/tech/stl -- Standard Template Library ... (comp.lang.c) - Re: how to add at the end of the linked list
... Just pass the pointer, no need to pass it by reference. ... > int prev; ... C++ Faq: http://www.parashift.com/c++-faq-lite ... http://www.josuttis.com -- C++ STL Library book ... (comp.lang.cpp) - Re: segmentation fault
... Dennis Schulz wrote: ... constant string and search the string: ... C++ Faq: http://www.parashift.com/c++-faq-lite C Faq: http://www.eskimo.com/~scs/c-faq/top.html alt.comp.lang.learn.c-c++ faq: ... Other sites: http://www.josuttis.com -- C++ STL Library book http://www.sgi.com/tech/stl -- Standard Template Library ... (comp.lang.c) - Re: tanjent function - can someone check my code
... > 5> returning a pointer in place of an int. ... C++ Faq: http://www.parashift.com/c++-faq-lite ... http://www.josuttis.com -- C++ STL Library book ... (comp.lang.c) - Re: help
... > problem is it only executes the first if statement and nothing else. ... > int month; ... C++ Faq: http://www.parashift.com/c++-faq-lite ... http://www.josuttis.com -- C++ STL Library book ... (comp.lang.cpp) |
|