Using std::string
will solve all your problems. It's particularly strange that you use C++ streams but C-style strings. Why?
Here's what your code would look like:
#include <string>
#include <iostream>
std::string fn()
{
std::string str = "Hello";
std::cout << str; // This prints the string Hello perfectly
// Some operations on string
return str;
}
int main()
{
std::string str = fn();
std::cout << str;
}
This makes your code cleaner, more robust, exception-safe, easier to read and write and possibly faster. Why in the world wouldn't you do it? (To be fair, there are situations where std::string
isn't appropriate, but first, beginners rarely encounter them, and second, such situations typically also outrule C++ streams.)
As for your original solution...
I know I should not pass address of a local variable back to main as
that stack of the program is modified.
Great :) But then why do you do it anyway?
But still if I use cout << *ptr then the output is just the first
character "H"
Besides the undefined behaviour resulting from returning a pointer to something that doesn't exist anymore, this sort of thing would happen even with a valid char*
. After all, dereferencing a char*
is not different from dereferencing an int*
or a double*
. It simply yields a char
, and printing a char
prints, well, a character.
int *i = new int(123);
std::cout << *i; // prints 123
double *d = new double(0.5);
std::cout << *d; // prints 0.5
char *c = new char('x');
std::cout << *c; // prints x
The fact that there may be more characters stored in memory right after that one dereferenced char
is irrelevant. You deliver a char
to std::cout
, nothing more. If you deliver a char*
, everything is different, because std::cout
then knows that it must "look for more characters".
Again, using std::string
, you don't need to care for these things.
I solved the problem by using a dynamically allocated memory for the
array using "new".
Not a good solution, because then you have the issue of who deletes the string. Without a delete[]
somewhere at the right location in your code, the memory occupied by the string will never be released until your program terminates, which can lead to memory leaks and your end users wondering why YourProgram.exe suddenly takes 800 MB in the Windows Task Manager :)
Again, use std::string
. It frees the allocated memory automatically when it's no longer needed.