boomerang061797
asked on
Simple pointer/function question
I'm having a problem getting a pointer to return a valid value when called as a parameter to a function. Here goes.
MyFunction(MyStruct *p)
{
p = APIFunctionThatReturnsPoin terToAData base();
}
MyStruct *p = 0;
MyFunction(p);
The value of p is valid inside the function but not after the function call. Why? Aren't I calling by reference?
MyFunction(MyStruct *p)
{
p = APIFunctionThatReturnsPoin
}
MyStruct *p = 0;
MyFunction(p);
The value of p is valid inside the function but not after the function call. Why? Aren't I calling by reference?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
nope, you are passing by value that which p points to. Try
MyFunction(MyStruct &p)
(I think, I'm over 40 hours without sleep now <g>)
MyFunction(MyStruct &p)
(I think, I'm over 40 hours without sleep now <g>)
ASKER
You are right and I found out just before I read your answer. :-) The problem was that I was setting my pointer to point to a local variale which contained the address from the API function. It was hard to see and I was getting put off by the fact that the API function returns a pointer to a variable type instead of a copy of the variable.
MyFunction(MyStruct &ms)
{
APIType type = typevalue;
MyStruct *temp_struct;
temp_struct = type.GetAPIMyStructType();
ms = *temp_struct;
}
MyStruct ms2;
MyFunction(&ms2);
I got around the problem by defining a temp_struct variable and returning its value to a functionparameter reference. Any Better solutions?
MyFunction(MyStruct &ms)
{
APIType type = typevalue;
MyStruct *temp_struct;
temp_struct = type.GetAPIMyStructType();
ms = *temp_struct;
}
MyStruct ms2;
MyFunction(&ms2);
I got around the problem by defining a temp_struct variable and returning its value to a functionparameter reference. Any Better solutions?
Nope, because that refers to parameters, and your fn doesn't take any.
Pass by value means copy the parameters (the fn gets its own copy and can't damage the originals)
void fn(int eeek)
{
eek = 20; // han no effect to caller
}
int blah = 200;
fn(blah);
cout << blah << endl; // blah = 200
Pass by reference menas that the fn gets the original values and can modify them.
void fn(int eeek)
{
eek = 20; // affects callers value
}
int blah = 200;
fn(blah);
cout << blah << endl; // blah = 20
But these apply to paramters, and yoiur fn doesn't have any, only a return value.
PS: the API takes one of your own structs, eh?