[EMAIL PROTECTED] wrote:
On Tuesday 22 November 2005 14:31, [EMAIL PROTECTED] wrote:
Ummmm ...
Coding 3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
somefunction()
{
char *string2 = "some words";
return string2;
}
int main (void)
{
char *string;
string = somefunction();
printf ("\n\nString is: %s\n\n", string);
return 0;
}
somefunction returns string2 which is trash!
formally: The scope of string2 does not extend to main!
(even if it works, and it might, it's WRONG)
What are you talking about ?
Tell me why it is trash.
"some words" is not a global variable in somefunction().
It is not global, yes.
but char *somefunction() is global to main which is the address of
the first character in "some words".
And string = somefunction() assigns the address of the first character in
"some words" to string.
So, when I print string, I get the result.
I can even re-write my preferred code as:
char *
somefunction()
{
same as original.........
}
int main (void)
{
printf ("\n\nString is: %s\n\n", somefunction());
return 0;
}
to make it even more readable.
There is no rule to say that the storage used for "some words" shall be intact
after somefunction() returns. It might be, and your example might work, but
it's still illegal.
After somefunction() returns, it has the address of the first character
in "some words".
I assign that address to string. I print the contents of that address up
to character '\0'.
This is done by printf.
This is a fundamental concept you're missing.
James
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html