puzzlecracker said:
Why would this work? - and it does! any thoughts?
#include<stdio.h>
void init(char **str){ *str="Awesome"; }
main(){
char * str;
printf("address: %d\n", str);
init(&str);
printf("address: %d\n", str);
printf("string:\'%s\' has %d characters \n", str,strlen(str));
}
It "works" because behaving as you expect is one of the infinitely
many possible consequences of undefined behavior.
Here's a corrected version of your program that (almost) avoids the
undefined behavior:
#include <stdio.h>
#include <string.h>
void init(char **str){ *str="Awesome"; }
int main(void)
{
char *str;
printf("address: %p\n", (void*)str);
init(&str);
printf("address: %p\n", (void*)str);
printf("string:\'%s\' has %d characters \n", str, (int)strlen(str));
return 0;
}
I say "almost" because it still uses the value of an unitialized (and
therefore indeterminate) variable in the first printf() call.
You could probably get away without the void* casts, since void* and
char* are effectively compatible as parameters, but IMHO it's good
style to use it anyway. (I've argued before that all casts should be
considered suspicious. Arguments to printf-like functions are a rare
case where casts are often required, because there is no implicit
conversion to the proper type.)
But as you said elsewhere in this thread, none of the problems I
corrected are directly relevant to what you're asking about.
The variable str is a pointer to char; effectively it points to a
string. The init() call changes the value of str, so it points to a
string whose value is "Awesome" (with a trailing '\0', of course).
(The string itself isn't copied.) This string is statically
allocated, so there's no problem referring to it after leaving the
init() function.