By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,649 Members | 696 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,649 IT Pros & Developers. It's quick & easy.

problems with Pass by Reference

P: n/a
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.

Sep 18 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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;
}

--

Frederick Gotham
Sep 18 '06 #2

P: n/a
Frederick Gotham wrote:
>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?

--
// morten
Sep 18 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.