December 30th, 2012, 05:23 AM
Question about passing pointer to function
i'm reading about memory allocation, and i saw an example of a wrong way and a right way to allocate memory from functions.
i have a question about it:
why is this wrong:
void func(int *p)
p = (int *) malloc(3*sizeof(int));
int *pm = NULL;
and this is right:
why isn't the allocated memory using the first way accessible?
void func(int **p)
*p = (int *) malloc(3*sizeof(int));
int *pm = NULL;
doesn't p hold pm's address?
thanks in advanced!
December 30th, 2012, 08:51 AM
When you declare local variables in a function, there are two actions performed by the compiler. One is declaring the variable of that type, second one is initializing the value for the variable.
In your example, the first program can't send any values to the function ie (pm) has no value. However, in the second case the address of the pointer is passed to the function and double declared here is initialized.
December 30th, 2012, 09:11 AM
But in the first example pm does have a value. NULL is a value, not the absence of one.
In the first example pm is a number (currently 0). It represents a location in memory (currently an invalid location) but it is still a number. And the normal rules when calling a function with parameters still apply: each value is a copy of the original. pm in main() will be copied to p in func. Modifying p is useless because you're modifying the copy.
The second example has func() receiving a copy of &pm, but that's fine because that copy has the same value and it's the value we actually care about: a location in memory. The function can then go off to that location and do whatever it wants (such as treat it as a pointer and modify the value being pointed to). There you're not actually modifying the copy itself.
main | pm = NULL |
------------ V --------
func | p = NULL |
main | &pm | -> | pm = NULL |
--------- V ------- ^ ------------
func | p | -----+ *p
December 30th, 2012, 10:08 AM
December 30th, 2012, 10:53 AM
and just want to make sure i got it right:
is that pretty much the different?