Re: pass by reference



squid wrote:
I have a small program that passes a pointer to a function, the
function uses malloc to allocate some memory for it. When I return
the pointer in the function return value I can use it in the calling
function.

Correct.

But I am unable to use the pointer I passes as a
parameter.

I assume that you mean something like this:

void AllocateSomething(char *pt)
{
pt = malloc(100);
}

and call it with:

...
char *something;
AllocateSomething(something);
...

and expect the calling "something" to reflect the malloc'ed buffer?

As you have found, this won't work, because C doesn't have "pass by reference". Rather, C uses "pass by value", and you cannot change this.

You can, if you really need, do something similar to pass by reference, and that is by explicitly passing the address of a variable. (Note, however, that you are passing the address "by value".)

void AllocateSomething(char **pt)
{
*pt = malloc(100);
}

and call it with:

...
char *something;
AllocateSomething(&sometihng);
...


I am using Visual Studio C++ Express Edition. The program
compiles and runs.
[...snip code ...]

Well, the code you posted "works" because you are not relying on pass by reference, and instead return the value from the function.


--
Kenneth Brody
.


Quantcast