Reputation: 79
my function prototype is this.
int * f4(int parm);
my function looks like this
int * f4(int parm)
{
return &parm + 1;
}
Is my return type correct for this? because it isn't doing anything when I call the function.
this is my call
int *pointer1;
pointer1 = f4(319);
cout << pointer1 << endl;
it returns the address of the pointer, but I need it to return the value, but I can't seem to get it to work.
using
cout << *pointer << endl;
just displays 0
Upvotes: 2
Views: 122
Reputation: 182639
The problem is the object parm
is local to that function. It's not legal to take and keep (i.e. return) a pointer to it after the function invocation ends.
In other words, parm
"lives" while the function exists. When the function returns all its local objects (such as parm
) "die".
As crush
notes in the comments, pointer1
becomes an invalid pointer, also affectionately called a "dangling" pointer.
so show the correct way to do it!!
As requested, there are a few ways to "correctly" do this:
Return parm + 1
directly, and change the return type of the function. It doesn't sound like you really need a pointer
Take the parameter as a pointer (or reference, this is C++) and increment its pointed value. You can also return it if you so desire - returning it is valid since it comes from outside the function
Add a static static int sparm; sparm = parm + 1
and return a pointer to sparm
. This will make your function non-reentrant but it will work: static
objects don't die when the function invocation ends
Allocate (ugh! don't!) some memory for a pointer and return that
Upon reading the code more carefully, it is quite clear that pointer is never valid. From the start it's one slot beyond the memory available as parm
.
Upvotes: 6
Reputation: 224944
Returning a pointer to a local variable is bad news. parm
is a function parameter, and so is local to f4
. You're returning a bad pointer to the caller and then trying to dereference it. That will only end in tears.
Upvotes: 3