问题
I had a programming assignment a while back where I stumbled upon this little problem: when I gave a function a pointer as a parameter, I could not change the address it pointed at. I solved that by returning the new adress I wanted the pointer to point to. But I am still wondering why it's not possible to manipulate a pointer parameter because all memory allocating functions work with a return value as well instead of a parameter list.
Was I possibly doing something wrong? Or is it really not possible to change the pointee? Does anyone have an explanation?
Example:
void foo(int *ptr)
{
ptr=malloc(sizeof(int));
} /* after calling this function I would
expect the pointee to have changed to the
newly allocate memory but it stays NULL*/
int main()
{
int *ptr=NULL;
foo(ptr);
return 0;
}
回答1:
Memory allocating functions return the pointer value, so it is generally assigned to a pointer.
Passing a pointer to a function as an argument is a different story, because changing it won't change the original (pass by value). That's why we use pointers in these cases, to give the address of a variable and change its value in the function.
If you need to pass a pointer instead, and change what it points to, use a pointer to a pointer!
void
my_function(int **pointer)
{
*pointer = &something; // will change the pointer address
}
int *my_pointer = &something_else;
my_function(&my_pointer);
回答2:
It's because all parameters are passed by value in C. If you call a function with a pointer parameter you may change that pointer in the function but this will have no effect on the caller's value of the pointer.
If you need to communicate a modified pointer back to the caller, returning the modified pointer is the way to go. Note that this also only passes a value back.
Another way would be to pass the address of a pointer (i.e. a pointer to a pointer). The called function can then store a new pointer value at the given address.
来源:https://stackoverflow.com/questions/32405685/assigning-a-new-adress-to-a-pointer-in-a-function-not-possible