I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. Could anybody give me any reason?
void memory(int *
In your first call to memory:
void memory(int * p, int size)
Realize that you are passing a VALUE to memory(), not an address. Hence, you are passing the value of '0' to memory(). The variable p
is just a copy of whatever you pass in... in contains the same value but does NOT point to the same address...
In your second function, you are passing the ADDRESS of your argument... so instead, p
points to the address of your variable, instead of just being a copy of your variable.
So, when you call malloc like so:
*p = (int *) malloc(size*sizeof(int));
You are assigning malloc's return to the value of the variable that p
points to.
Thus, your pointer is then valid outside of memory().