Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pointers lossing values when the function returns

Status
Not open for further replies.

Mthales

Technical User
Feb 27, 2004
1,181
GB
I'm sure this is just me being really silly - and if the keyword search was working I'd probably find the answer there - but it's not so I'm gonna ask:

I have a function that takes a couple of pointers typed to be instances of classes that I have defined. Inside this function I'm setting these pointers to be new objects of the relevnt types. However when the function returns control to it's calling function and I check the values of these pointers they are still at there inital Null values - not the ones set in the function.

Could someone please try and tell me where I'm going wrong
Thanks for your help
 
Code:
void foo ( char *p ) {
  p = new char[10];
}
int main ( ) {
  char *str;
  foo( str );   // This does not update str
}

There are several ways of fixing this
Code:
char *foo ( void ) {
  char *p = new char[10];
  return p;  // return result
}
void bar ( char **p ) {
  *p = new char[10];  // pointer to a pointer
}
void baz ( char * &p ) {
  p = new char[10];  // reference to a pointer
}

int main ( ) {
  char *str;
  str = foo();
  bar( &str );
  baz( str );
}

--
 
Salem Thank you very much for the advice I think doing it with the reference to a pointer method has fixed it. I'm not sure I totally understand how but it works!
 
When you pass a [tt]char*[/tt] argument to a function, the function gets a copy of that pointer. In Salem's foo function, the copy of the pointer is changed to point at a string. Then the function returns, the copy is destroyed (making its existence useless), and you're left with the original, which was untouched and still points to whatever it pointed to before.

Now, if you instead passed the address of that pointer (that is, a pointer to the pointer), then the function would get a copy of that address. It could then change the contents of that address, making the original pointer point elsewhere. The function would then return, and the copy of the address would be destroyed; however, it would have fulfilled its purpose because the function actually used its value to "find" and change your original pointer, which is still changed after the function returns.

The reference is just a simple way of accomplishing that exact same thing. It just has easier syntax because it takes care of the "get the address of the pointer" and "dereference the address" parts automatically.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top