[snip]
> >>>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;
> >>>}
> >>>
O Plameras was once rumoured to have said:
> 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.
No, you're missing it. Here's a slightly nastier example[1] which
demonstrates why what you're doing is wrong and should not be done.
---BEGIN---
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
somefunction()
{
auto char string2[] = "some words";
return string2;
}
void
anotherfunction()
{
auto int i,r[50];
/* build a 'random' sequence on the stack to prove the point. */
for (i = 0; i < 50; i++) {
r[i] = (i*13)%256;
}
}
int main (void)
{
char *string;
string = somefunction();
anotherfunction();
printf ("\n\nString is: %s\n\n", string);
return 0;
}
---END---
string still contains a pointer to the start of the string "some
words", right?
Now, before chickening out and running it, predict the outcome.
This is why you don't return pointers from stuff defined in local
subroutine scope.
C.
[1] I expect Benno and Erik to immediately spot the subtle difference. ;)
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html