need help with a piece of code

In the following code

char *Hello()
{
char str[30];
strcpy(str,"Hello there!");
cout<<"in fxn "<<str<<endl;
return str;
}
int main()
{
cout<<"in main "<<Hello()<<endl;
printf("%s",Hello());
system("pause");
}

output:
in fxn Hello there!
in main ╠╠╠╠╠╠╠╠
in fxn Hello there!
Hell|°(Press any key to continue . . .

if i use string instead of char *Hello() i get the desired output but otherwise it returns some garbage values as you can see. So i am unable to understand why?
str is local in Hello(). It only exist inside that function and when the function ends the array will no longer exist. So in main you try to print the content of a non-existing array.
Last edited on
closed account (zb0S216C)
You're returning the address of a local array. Once Hello() finishes its execution, all local, non-static, variables/object are removed from the stack. The address you're returning pertains to a local array. So when you access the address during the printf() call, the address is invalid, and therefore, contains garbage.
Your best bet is to print the string during the call to Hello().

Also, you're using C++, so use std::string.

Wazzak
Thanks alot guys ..... really appreciate it
Topic archived. No new replies allowed.