problems with Pass by Reference

B

bg_ie

I have a function as follows -

long Read (char* databuf)
{
/* start missing */

databuf = new char [datasize];
file.read (databuf, datasize);
return datasize;
}

I call it as follows -

char* databuf = NULL;
long datasize = Read (databuf);

The problem is that databuf is still NULL after that call to Read(). I
understand why, but how should I do this?

Thanks,

Barry.
 
F

Frederick Gotham

The problem is that databuf is still NULL after that call to Read(). I
understand why, but how should I do this?

You want a reference to a pointer:

long Read(char *&p)
{
p = new char[10];
return 10;
}

int main()
{
char *p;

Read(p);

delete [] p;
}
 
M

Morten V Pedersen

Frederick said:
The problem is that databuf is still NULL after that call to Read(). I
understand why, but how should I do this?

You want a reference to a pointer:

long Read(char *&p)
{
p = new char[10];
return 10;
}

int main()
{
char *p;

Read(p);

delete [] p;
}

Yes you need a *reference to pointer* or *pointer to pointer* the reason
is that you actually passing the pointer by value - what does that mean?

When you call Read(..) a temp copy of you databuf pointer is created
pointing to NULL, this is then passed to Read(..) - so every change you
make to the databuf inside Read(..) is only performed on the temp copy
and when Read(..) returns the original databuf will remain unchanged.

Did that make sense to you?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top