this program returns a pointer to a structure.
When i print the contents, the name is not being displayed properly, where as the other tw
The problem here is that you're returning a pointer to a local variable. Local variables goes out of scope once the function they are defined in returns. That means that the pointer you return will point to unallocated memory after the function returns. Using that pointer will lead to undefined behavior.
There are three ways to solve this:
static
local variable. It also will have the lifetime equal to the program.Points 1 and 2 have a problem in that then you can only have a single object. If you modify that object, all places where you have a pointer to that single object will see those changes.
Point 3 is the way I recommend you go. The problem with that is that once you're done with the object, you have to free the memory you allocate.