|
-
August 6th, 2010, 04:31 AM
#2
Re: malloc inside a function
 Originally Posted by galapogos
Hi,
I'm trying to pass a pointer to a function, and then have the function allocate some memory for that pointer. Is this possible?
Yes it is possible. The problem you're having is that you are changing the value of a temporary within a function.
When you pass a parameter by value, the function makes a temporary copy. When that function returns, that temporary is gone. A pointer is nothing but a value you're passing, and the same rules apply.
To change a parameter value and have it reflect back to the caller, you either pass a pointer to the variable, or a reference to the variable. So you either pass a pointer to the pointer, or a reference to the pointer.
I tried the following code, but doesn't seem to work.
Just like this code won't work:
Code:
void foo(int x)
{
x = 10;
}
int main()
{
int p = 0;
foo( p );
// p is still 0. Why isn't it 10?
}
Same principle.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|