Hello all,
I have a basic question in C++.
In the code below, I am creating a local variable in a function and returning its address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
using namespace std;
int* foo();
int main(int argc, char* argv[])
{
int *ptr = foo(); //line 1
int val = *foo(); //line 2
int *p = new int; //if these two lines are removed both give result '5'
*p = 9;
cout<<*ptr; //first cout
cout<<"\n"<<val; //second cout
return 0;
}
int* foo()
{
int a = 5;
int *c = &a;
return c;
}
|
My understanding is, the variable is local to the the function. So returning its address does not sound like a meaningful thing to do. However, line 2 (commented), seems to gives the value '5'. line 1 gives a junk value (although it can give the correct value if I get lucky.For example, if I remove the line int *p = new int; below it).
Could somebody explain to me from a memory stand point, what the differences between
1 2
|
int *ptr = foo();
int val = *foo();
|
are and what does it mean to return an address of a local variable created in a function?
Also, if the first one is wrong, what confused me is the value statements in Gary Bradsky's Learning opencv
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
IplImage* doPyrDown(
IplImage* in,
int filter = IPL_GAUSSIAN_5x5
) {
// Best to make sure input image is divisible by two.
//
assert( in->width%2 == 0 && in->height%2 == 0 );
IplImage* out = cvCreateImage(
cvSize( in->width/2, in->height/2 ),
in->depth,
in->nChannels
);
cvPyrDown( in, out );
return( out );
};
|
This looks similar to line 1, (which gives junk value)
Thanks!