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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer

Status
Not open for further replies.

fheyn

Programmer
Mar 22, 2001
198
DE
hi,

void f(MyStruct* p)
{
p = new MyStruct;
}

is called like this : f(ptr1);

with ptr1 declared as MyStruct* ptr1;

I think passing the pointer as above is incorrect 'cause

p has a correct value but ptr1 is 0 after the function

call.

so what's wrong ?

thanks in advance
 
The new MyStruct is local to f(), so the structure is lost when the function returns. However, since the pointer isn't deleted inside the function, you'll have a memory leak.

If you want to use the new MyStruct, you'll need to write something like this:
Code:
MyStruct* f(MyStruct* p)
{
   p = new MyStruct;
   return p;
}

Lee
 
you could also pass in a reference of the pointer:

Code:
void f(MyStruct &p)
{
   p = new MyStruct;
}
[\code]

either way works.
 
When you pass a pointer, you're actually passing a copy of a pointer, unless you pass the pointer as a reference like this:
Code:
void f(MyStruct*[COLOR=red]&[/color] p)
{
   p = new MyStruct;
}
but some people find that syntax a bit confusing or they prefer a more standard C way of doing it, which is to pass a pointer to the pointer you want to modify:
Code:
void f(MyStruct*[COLOR=red]*[/color] p)
{
   [COLOR=red]*[/color]p = new MyStruct;
}
 
thank you guys,

I tried it, it works !
 
cpjust, so then
Code:
void f(MyStruct &p);

creates a new "version" of the pointer by reference?

and

Code:
void f(MyStruct *&p);

actually references the same memory of the original pointer without creating a new object pointer?
 
Your first example is to a structure named p, and is NOT a pointer to the structure. If you pass that function a pointer, you'll probably get an error when you compile unless you dereference the pointer when you call the function.

Lee
 
Yes, SDowd. Your first example passes the reference to a MyStruct structure, where the second pases a reference to a MyStruct pointer.

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top