It just so happens that this works for your compiler in this particular case. The array x is only valid in the function where it is declared. The fact that the memory locationstill happens to be set to "hi" after the function returns is simply because the computer hasn't had the need to overwrite it yet - but that is not guaranteed. The best way to pass a string out of a function is like this:
Code:
void foo(char f[])
{
strcpy( f, "hi");
}
int main(void)
{
char f[10];
foo(f);
printf( "%s", f);
return 0;
}
An alternative way is this:
Code:
char* foo()
{
char * x = malloc(10*sizeof(*x)) ;
strcpy( x, "hi");
return x;
}
int main(void)
{
char *f;
f = foo();
printf( "%s", f);
free(f);
return 0;
}
But (in my opinion) the 2nd way is dangerous because you are malloc()ing and free()ing in different functions and could forget for one branch of the code leading to memory leaks. Go with the 1st way.
Scribbler: your foo() function writes to a random, unallocated memory location - that is a memory leak.
edit:: must learn to type faster...