Re: pass by reference
- From: Kenneth Brody <kenbrody@xxxxxxxxxxx>
- Date: Tue, 28 Jul 2009 11:34:54 -0400
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[...snip code ...]
compiles and runs.
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
.
- References:
- pass by reference
- From: squid
- pass by reference
- Prev by Date: ●▂●Find all the new Air Force One Shoes, Nike Air Force One Sneakers, Jordans Retro ect in China. High Quality and low price ***, Welcome to visit---www.fjrjtrade.com
- Next by Date: Re: Help a beginner - simple lowercase to uppercase and so on function
- Previous by thread: Re: pass by reference
- Next by thread: Code Review - is this code shit
- Index(es):