Donos said:
Hello
I have the following program,
void getValue(unsigned char* pVal)
The paramater pVal is a pointer value. It is passed by copy, that is, what
ever pointer is passed as the paramater is copied into the local variable
pVal.
The local variable pVal is changed. But remember, it's just a local
variable. It's just a copy of the addess/pointer that was passed it. Once
this function returns, the temporary varaible is destroyed.
}
unsigned char* allValues()
{
unsigned char* a;
-------------------
// Some code in here
-------------------
return a;
}
Somehow am not able to get the character pointer "a" back into "pVal".
Why this is happening?
As stated, because you are only changing the local variable pVal, not
whatever was passed in. I'm guessing you wanted to change the pointer that
was passed in. If you wish to change the variable that is passed it you
need to pass it by reference. There are 2 ways to do this, a pointer to the
variable, or a reference to the variable. In C the only way was a pointer
to the variable. In C++ we also have references to variables. If you
change getVal like:
void getVal( unsigned char*& pVal )
{
pVal = allValue();
}
then the variable itself that is passed by as the parameter is changed. The
C way was to pass a pointer to the variable.
void getVal( unsigned char** pVal )
{
*pVal = allValue();
}
Just understand, that if you are not passing a reference, you are passing a
copy, even if they are pointers, it's still a copy of the pointer.