hi everybody,

these two codes returns pointer to an object declared and defined within the function. yet both of them prints the correct value of the variable c in main(the values of variable c should have been destroyed when the call is over.).
the first code gives the warning.
but second do not..(all compilations in g++ )

const char *f()
{
	char c;
	cout<<"enter : ";
	cin>>c;
	return &c;
}

int main()
{
	const char *c = f();
	cout<<"the value is "<<*f()<<endl;
}
const char *f()
{
	return "hello world\n";
}

int main()
{
	const char *c = f();
	cout<<c<<endl;
}

please help.....
thanx.....

>>return &c;
That is returning a pointer to an object that was created on the stack. Your compiler correctly flagged it as a warning, but its is really an error. It is an error because variable [c]c[/b] is destroyed as soon as the function f() returns, and consequently the line in main() is receiving an invalid pointer.

The second example is ok because string literals are not put on the stack but reside in global space (the heap). You can safely return objects or pointers to objects that reside in the heap because they are unaffected when a function returns to its caller.

thanx....
but still the example one prints the value correctly in main?????
how is that possible????

AD already answered that:

The second example is ok because string literals are not put on the stack but reside in global space (the heap). You can safely return objects or pointers to objects that reside in the heap because they are unaffected when a function returns to its caller.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.