[EMAIL PROTECTED] wrote:


I find this interesting.


<snipped>

char* somefunction()
{
       char string2[] = "some words";
       return string2;
}
--------------------------------------
doesn't


Hi Yiz,

A couple of people have explained why the above does
not work.

My attention will focus on How to make it work.

As suggested, the main requirement is to have a pointer that you can use to manipulate
the string around. So, I modified the function to get,

char*
somefunction()
{
char * string1; /* I define a char pointer since your array is char string */
      char string2[] = "some words";
string1 = malloc(11); /* In the context of this program, it is sufficient to set aside 11 bytes */
      strcpy(string1,string2);   /* I duplicate string2 into string1 */
return string1; /* I return address of string1 to become the value of somefunction() */ /* which is passed on to main() and then printed by main() */
}

int main(void) /* I added main function to complete a test program */
{
printf("\nThe string is: %s\n", somefunction()); /* somefunction() initialised and printed */
      return 0;
}

You appear to be a keen user of C.
One suggestion, learn to use GDB ( http://www.gnu.org/software/gdb/ ) if you have'nt yet. This package will help you understand further why the original 'somefunction()' did not work.

Hope this helps.

O Plameras
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to